Java下載圖片到本地
阿新 • • 發佈:2018-12-21
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("下載的圖片不存在!"); } }