JAVA WEB IO流下載檔案
阿新 • • 發佈:2018-12-27
@ResponseBody @RequestMapping("/file") public void findfile(String fjid, HttpServletResponse response) throws IOException { try { //獲取檔案存放的路徑 TFGyFjxx bean = tfGyFjxxService.findByFjid(fjid); String url = bean.getFjdz().replace(fjid, bean.getFjmc()); File file = new File(url); String newFileName = bean.getFjmc(); if (!file.exists()) { //如果檔案不存在就跳出 return; } InputStream in = new BufferedInputStream(new FileInputStream(file)); OutputStream out = new BufferedOutputStream(response.getOutputStream()); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("合成作戰" + newFileName, "UTF-8")); response.setContentLength((int) file.length()); //讀取檔案流 int len = 0; byte[] buffer = new byte[1024 * 10]; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.flush(); out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } }
後端程式碼是這樣的,前端只要注意別用ajax提交就ok,一般用a標籤或者window.location.href就行