Spring MVC File Download instance details, springmvc

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.