方式一
情况1:
@PostMapping("/download1")public ResponseEntity<byte[]> download1() throws Exception {// 下载文件目录位置FileInputStream fis = new FileInputStream("C:\\Users\\wsd\\Pictures\\susu.jpg");// 一次读取bytes.length 个字节并将读到的字节放入bytes数组中byte[] bytes = new byte[fis.available()];fis.read(bytes);fis.close();HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.add("Content-Disposition", "attachment;filename=" + "download-name-001.jpg");// 将要下载的文件的字节流返回给浏览器return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);}
情况2:
// 下载文件名包含中文,需要解析@PostMapping("/download2")public ResponseEntity<byte[]> download2() throws Exception {// 下载文件目录位置FileInputStream fis = new FileInputStream("C:\\Users\\wsd\\Pictures\\susu.jpg");// 一次读取bytes.length 个字节并将读到的字节放入bytes数组中byte[] bytes = new byte[fis.available()];fis.read(bytes);fis.close();HttpHeaders httpHeaders = new HttpHeaders();String downloadFileName = "下载命名-001.jpg";httpHeaders.add("Content-Disposition","attachment;filename=" + URLEncoder.encode(downloadFileName,"UTF-8"));// 将要下载的文件的字节流返回给浏览器return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);}
方式二
// 无返回值@PostMapping("/download3")public void download3(HttpServletResponse response) throws IOException {// 下载文件目录位置FileInputStream fis = new FileInputStream("C:\\Users\\wsd\\Pictures\\susu.jpg");// 一次读取bytes.length 个字节并将读到的字节放入bytes数组中byte[] bytes = new byte[fis.available()];fis.read(bytes);fis.close();String downloadFileName = "下载命名-001.jpg";response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(downloadFileName,"UTF-8"));response.setContentType("application/octet-stream");OutputStream os = response.getOutputStream();os.write(bytes);os.flush();os.close();}
方式三
使用 try-with-resources
@PostMapping("/download4")public String download4(HttpServletResponse response) throws IOException {JSONObject jsonObject = new JSONObject();response.reset();response.setCharacterEncoding("utf-8");String downloadFileName = "下载命名-001.jpg";response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(downloadFileName,"UTF-8"));response.setContentType("application/octet-stream");// 下载文件目录位置String filePath = "C:\\Users\\wsd\\Pictures\\susu.jpg";// 使用 try-with-resourcestry (FileInputStream fis = new FileInputStream(filePath);OutputStream os = response.getOutputStream()) {byte[] buffer = new byte[fis.available()];int len;while ((len = fis.read(buffer)) != -1) {os.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();}jsonObject.put("success", "下载成功");return jsonObject.toJSONString();}