作用
下载远程图片
代码
public static void download(HttpServletResponse response, String fileUrl, String fileName) {
if (EmptyUtil.notEmpty(fileUrl)) {
try {
//把 文件字节长度给 byte[], 输入流读取到 byte[] 中
byte[] buffer = getFileBytes(fileUrl);
if (EmptyUtil.notEmpty(buffer)) {
//输出流
OutputStream os = null;
try {
String contentTypeValue = "application/octet-stream";
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 设置响应头信息
response.setContentType(contentTypeValue);
//定义输出流
os = response.getOutputStream();
//把 输出流写入 字节byte[]中数据
os.write(buffer, 0, buffer.length);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (os != null)
os.close();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static byte[] getFileBytes(String fileUrl) {
//文件全路径 :sysFile.getStorePath()
File file = new File(fileUrl);
if (!file.exists()) {
return null;
}
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
return data;
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}