SpringMVC環境下匯出檔案
阿新 • • 發佈:2019-02-06
很簡單的程式碼,不多說,直接上程式碼
這是後臺程式碼
@RequestMapping("/download.do") public String download(int id, HttpServletRequest request, HttpServletResponse response) { User user = userService.getById(id); response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;fileName=" +"ldk.png"); String path = user.getQrPath(); //獲取資料 //########################下載檔案begin######################## try { InputStream is = new FileInputStream(new File(path)); OutputStream os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = is.read(b)) > 0) { os.write(b, 0, length); } // 這裡主要關閉。 os.close(); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //########################下載檔案end######################## // 返回值要注意,要不然就出現下面這句錯誤! //java+getOutputStream() has already been called for this response return null; }
前端只需要一個連結就可以了
<input type="button" onclick="window.location.href='${ctx}/users/download.do?id=${user.id}'" value="匯出"/>
結果就是