What you don't know about SpingMVC file download?
File upload and download are usually very practical in the project. Here we will sort out the file download. The file upload implementation will be completed later. File downloads are mostly used to download template files, which are quite a lot used in projects. Today, we have used it for reference and use by porters. It has been verified to be correct.
(1) Foreground implementation
The front-end implementation is very simple, not as complicated as File Upload. You only need to provide a hyperlink to link to the back-end processing method and pass the file name into the Controller.
(2) background processing
The Controller in the background mainly handles the following issues:
① Locate the Template File Based on the file name
② Set the response format, file header, and encoding
③ Read the template file content in the form of a stream and write it to the output stream
④ Close the input/output stream
(3) The implementation code is as follows:
① Foreground:
<A href = "$ {base}/downloadTemplate? FileName=abilityTemplate.xlsx "> template download </a>
② Background:
@ RequestMapping (value = "/downloadTemplate", method = RequestMethod.GET)
Public String downloadAbilityTemplate (String fileName, HttpServletRequest request, HttpServletResponse response ){
Response. setCharacterEncoding ("UTF-8"); // sets the Encoding
Response. setContentType ("multipart/form-data"); // set the type
Response. setHeader ("Content-Disposition", "attachment; fileName =" + fileName); // set the response Header
Try {
String filePath = Config.GetValue("Path ");
// Obtain the directory of the template file in the configuration file
String path = request. getSession (). getServletContext (). getRealPath ("/") + filePath;
// Obtain the relative directory of the template file
InputStream inputStream = new FileInputStream (new File (path + File.Separator+ FileName ));
OutputStream OS = response. getOutputStream ();
Byte [] B = new byte [2048];
Int length;
While (length = inputStream. read (B)> 0 ){
OS. write (B, 0, length );
} // Read the template file while writing the output stream
OS. close ();
InputStream. close (); // close the stream
} Catch (FileNotFoundException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
Return null; // note that return null
}
(4) Notes:
① The returned model layer should be return null; otherwise, the following error occurs:
Java + getOutputStream () has already been called for this response
② The location of the template file can be stored as needed, as long as the full path of the file can be obtained in the background
In the class directory, obtain the following information:
// Obtain the path of the classes
String path = Thread. currentThread (). getContextClassLoader (). getResource (""). getPath ();
// Obtain the WebRoot directory:
String path = request. getSession (). getServletContext (). getRealPath ("/")