1、首先页面请求不可以用ajax请求,否则会将信息输出到控制台
var url = "${path}/pc/qrcode/downLoad.do?filename="+ 文件路径 +"&imgName=" +保存的文件名称;
window.location.href = url;
2、java代码
/**
* 下载图片到本地
* @param request
* @param response
* @param filename 文件路径
* @param imgName 保存的图片名称
*/
@RequestMapping("/pc/qrcode/downLoad.do")
public void download(HttpServletRequest request, HttpServletResponse response,
@RequestParam("filename") String filename, @RequestParam("imgName") String imgName){
String path = request.getRealPath("");
File file = new File(path+File.separator+filename);
FileInputStream is = null;
// 响应输出流
ServletOutputStream out = null;
if(file.exists()) {
try {
response.setContentType("application/x-jpg");
//设置头信息,内容处理的方式,attachment以附件的形式打开,就是进行下载,并设置下载文件的命名
response.setHeader("Content-Disposition","attachment;filename=\""+URLEncoder.encode(imgName,"UTF-8")+".jpg\"");
response.setHeader("Content-Transfer-Encoding","binary");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.flushBuffer();
is = new FileInputStream(file);
out = response.getOutputStream();
// 创建缓冲区
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
is.close();
out.flush();
out.close();
} catch (Exception e) {
log.error("ERROR:" + e);
} finally {
try {
is.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
log.info("下载的图片不存在!");
}
}