因项目需求要下载jpg图片但是-----因为通过超链接下载文件时,如果浏览器可以识别该文件格式,浏览器就会直接打开。只有浏览器不能识别该文件格式的时候,才会实现下载。
初期用window.open(链接)和window.location.href=链接都无济于事。
只有走后台用流的方式来下载,代码如下:
前台:
window.open('请求后台的链接‘);
后台:
@RequestMapping("/downByPath")
public void downLoadImagesByPath(String paths,String fileName,HttpServletResponse response) throws IOException{
//设置浏览器显示的内容类型为Zip (很重要,欺骗浏览器下载的是zip文件,就不会自己打开了)
response.setContentType("application/zip");
//设置内容作为附件下载 fileName有后缀,比如1.jpg
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
ServletOutputStream out = null;
try {
// 通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
InputStream inputStream = FileManageUtils.downLoadFile(paths);//此处是为了获得输出流
// 3.通过response获取ServletOutputStream对象(out)
out = response.getOutputStream();
int b = 0;
byte[] buffer = new byte[512];
while (b != -1) {
b = inputStream.read(buffer);
// 4.写到输出流(out)中
out.write(buffer, 0, b);
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null)
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}