Spring MVC File Download instance details, springmvc
Spring MVC File Download instance details
Read files
To download a file, first read the file content and store it in byte arrays. Here we use the tool class in spring to implement
import org.springframework.util.FileCopyUtils; public byte[] downloadFile(String fileName) { byte[] res = new byte[0]; try { File file = new File(BACKUP_FILE_PATH, fileName); if (file.exists() && !file.isDirectory()) { res = FileCopyUtils.copyToByteArray(file); } } catch (IOException e) { logger.error(e.getMessage()); } return res; }
This array is the content of the file, which will be output to the response for the browser to download.
Response to the downloaded file
The response header of the downloaded file is different from the general response header, which must be treated differently according to the user's browser.
I encapsulate the code that generates the response into a method so that all download responses can call this method to avoid repeated code writing everywhere.
Protected ResponseEntity <byte []> downloadResponse (byte [] body, String fileName) {HttpServletRequest request = (ServletRequestAttributes) RequestContextHolder. getRequestAttributes ()). getRequest (); String header = request. getHeader ("User-Agent "). toUpperCase (); HttpStatus status = HttpStatus. CREATED; try {if (header. contains ("MSIE") | header. contains ("TRIDENT") | header. contains ("EDGE") {fileName = URLEncoder. encode (fileName, "UTF-8"); fileName = fileName. replace ("+", "% 20"); // IE download file name space change + problem status = HttpStatus. OK;} else {fileName = new String (fileName. getBytes ("UTF-8"), "ISO8859-1") ;}} catch (UnsupportedEncodingException e) {} HttpHeaders headers = new HttpHeaders (); headers. setContentType (MediaType. APPLICATION_OCTET_STREAM); headers. setContentDispositionFormData ("attachment", fileName); headers. setContentLength (body. length); return new ResponseEntity <byte []> (body, headers, status );}
Note: Generally, the status code 201 is used for downloading files, but it is not supported by IE. It takes a lot of effort to find out the problem.
The file name is processed to prevent Chinese characters and spaces from causing garbled characters in the file name.
Controller Method
The return value must be processed in the controller.
@RequestMapping(value = "/download-backup", method = RequestMethod.GET) @ResponseBody public ResponseEntity<byte[]> downloadBackupFile(@RequestParam String fileName) { byte[] body = backupService.downloadFile(fileName); return downloadResponse(body, fileName); }
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!