項目中遇到文件下載,所以總結一下遇到的文件下載方式:
方法一,返回一個 ResponseEntity,響應實體返回一個字節數組,
public ResponseEntity<byte[]> exportData() throws IOException { HttpHeaders headers=new HttpHeaders(); headers.setContentDispositionFormData("attachment", new File(filePath).getName()); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(filePath)),headers, HttpStatus.CREATED); }
ResponseEntity用於構造標識整個http響應:狀態碼、頭部信息以及相應體內容。因此我們可以使用其對http響應實現完整配置。
方法二,通過向響應對象中寫入字符流的方式實現。
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("utf-8"); resp.setContentType("application/octet-stream"); resp.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("中國", "utf-8")+".txt"); PrintWriter os = resp.getWriter(); String path = this.getServletContext().getRealPath("/download"); Reader is = new BufferedReader(new FileReader(new File(path,"t.txt"))); int len=0; char[] buffer = new char[200]; while((len=is.read(buffer))!=-1){ os.print(new String(buffer,0,len)); } is.close(); os.close(); } }