根据URL下载文件/图片
根据URL下载文件、图片的方法
1、应用场景:远程文档服务器返回json结果,内容包括文件名称,文件路径,文件类型等信息,使用流(InputStream),通过文件路径去下载文件、图片。
远程文档服务器返回json结果如下图:
2、应用方法:
先将返回的结果(代码中的fileData)进行转换为Map,获取其中key为data的数据,如文件名,文件路径信息,然后设置请求头信息,需设置:
ContentType:multipart/form-data
Content-Disposition:attachment; filename="xxx.xx"
然后根据文件路径创建URL对象,在根据URL对象打开输入流InputStream,然后在使用OutputStream流输出;
3、特别注意:
因为文件名称可能为中文,所以需要进行转码,否则会乱码,这里会将中文替换为下划线_ 如下图所示:
这里要特别注意,文件名称编码格式不能使用UTF-8/GBK,需使用ISO-8859-1格式:
new String(fileName.getBytes(),"iso-8859-1");
下载的方法代码如下:
/**
* 通过URL下载文件
*
* @param fileData
* @throws IOException
*/
public static void downloadWithUrl(String fileData, HttpServletResponse response) throws IOException {
ObjectMapper om = new ObjectMapper();
Map<String, Object> map = om.readValue(fileData, Map.class);
Map<String, Object> data = ((List<Map<String, Object>>) map.get("data")).get(0);
String fileName = (String) data.get("file_name");
String path = (String) data.get("file_path");
//设置响应参数
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
// response.setHeader("Content-Disposition", " attachment; filename=" + fileName);//使用此会导致中文变“_”下划线
response.setHeader("Content-Disposition", " attachment; filename=" + new String(fileName.getBytes(), "iso-8859-1"));
InputStream is = null;
BufferedOutputStream outs = null;
try {
//创建数据流,执行下载
URL url = new URL(path);
is = url.openStream();
outs = new BufferedOutputStream(response.getOutputStream());
byte[] bytes = IOUtils.toByteArray(is);
outs.write(bytes);
} finally {
if (null != outs)
outs.close();
if (null != is)
is.close();
}
}
还没有评论,来说两句吧...