Java下载图片到本地

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("下载的图片不存在!");
        }
	}
	

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值