catalogue
1. Introduction
- Spring MVC can well support file upload, but MultipartResolver is not installed in the spring MVC context by default, so it cannot handle file upload by default. If you want to use spring's file upload function, you need to configure MultipartResolver in the context.
- The front end must set the method of the form to POST and the enctype to multipart / form data. Only in this case, the browser will send the file selected by the user to the server as binary data;
<form action="" enctype="multipart/form-data" method="post"> <input type="file" name="file"/> <input type="submit"> </form>
Introduction to enctype attribute
-
Application / x-www = form urlencoded: by default, only the value attribute value in the form field is processed. Forms with this encoding method will process the value in the form field into URL encoding.
-
Multipart / form data: this encoding method will process form data in the form of binary stream. This encoding method will also encapsulate the contents of the file specified in the file field into the request parameters, and will not encode characters.
-
text/plain: except for converting spaces into "+" signs, other characters are not encoded. This method is applicable to sending mail directly through forms.
2. File upload
(1) Import dependent packages uploaded by files
<dependencies> <!--File upload--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!--servlet-api Import a later version of--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> </dependencies>
(2) Configuring the spring MVC core configuration file
<!--File upload configuration--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- The encoding format of the request must be and jSP of pageEncoding Property is consistent so that the contents of the form can be read correctly. The default is ISO-8859-1 --> <property name="defaultEncoding" value="utf-8"/> <!-- Maximum upload file size, in bytes (10485760)=10M) --> <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="40960"/> </bean>
Parameter analysis:
attribute | describe |
maxUploadSize | Maximum length of uploaded file (in bytes) |
maxInMemorySize | Maximum size in cache |
defaultEncoding | Default encoding format |
resolveLazily | Postpone file parsing to catch file size exceptions in the Controller |
Note: the id of bena must be: multipartResolver, otherwise an error of 400 will be reported when uploading the file!
(3) Write front page
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post"> <input type="file" name="file"/> <input type="submit" value="upload"> </form> </body> </html>
(4) Write Controller
Main methods in MultipartFile interface
method | explain |
byte[]getBytes() | Returns the contents of the file as a byte array |
String getContentType() | Returns the content type of the file |
InputStream getInputStream() | Read the contents of the file and return an InputStream stream |
String getName() | Gets the parameter name of the multi part form |
String getOriginalFilename() | Gets the initialization name of the uploaded file |
long getSize() | Gets the size of the uploaded file in bytes |
boolean isEmpty() | Judge whether the uploaded file is empty |
void transferTo(File file) | Save the uploaded file to the target directory |
package com.yixin.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.*; @Controller public class FileController { //@RequestParam("file") encapsulates the file obtained by the name=file control into a CommonsMultipartFile object //If you upload CommonsMultipartFile in batch, it can be an array @RequestMapping("/upload") public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException { //Get file name: file getOriginalFilename(); String uploadFileName = file.getOriginalFilename(); //If the file name is empty, go back to the home page directly! if ("".equals(uploadFileName)){ return "redirect:/index.jsp"; } System.out.println("Upload file name : "+uploadFileName); //Upload path save settings String path = request.getServletContext().getRealPath("/upload"); //If the path does not exist, create one File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } System.out.println("Upload file storage address:"+realPath); InputStream is = file.getInputStream(); //File input stream OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //File output stream //Read write int len=0; byte[] buffer = new byte[1024]; while ((len=is.read(buffer))!=-1){ os.write(buffer,0,len); os.flush(); } os.close(); is.close(); return "redirect:/index.jsp"; } }
(5) Configure tomcat and start running
Since the memory of the file configured in the configuration file is less than 10M, select the corresponding file and click upload to download to the corresponding address.
We can also use the transferTo of CommonsMultipartFile to save the address.
(you can see that this method is relatively simple to save.)
@RequestMapping("/upload2") public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { //Upload path save settings String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //Upload file address System.out.println("Upload file storage address:"+realPath); //Write the file directly through the CommonsMultipartFile method (note this time) file.transferTo(new File(realPath +"/"+ file.getOriginalFilename())); return "redirect:/index.jsp"; }
Changing the submission address at the front end can also achieve the purpose of saving.
3. File download
(1) Write Controller
@RequestMapping(value="/download") public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{ //Address of the picture to download String path = request.getServletContext().getRealPath("/upload"); String fileName = "logo.jpg"; //1. Set response header response.reset(); //Set the page not to be cached, and clear the buffer response.setCharacterEncoding("UTF-8"); //Character encoding response.setContentType("multipart/form-data"); //Binary transmission data //Set response header response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8")); File file = new File(path,fileName); //2. Read file -- input stream InputStream input=new FileInputStream(file); //3. Write out file -- output stream OutputStream out = response.getOutputStream(); byte[] buff =new byte[1024]; int index=0; //4. Perform a write out operation while((index= input.read(buff))!= -1){ out.write(buff, 0, index); out.flush(); } out.close(); input.close(); return null; }
(2) Write front end
<a href="${pageContext.request.contextPath}/download">Click download</a>
(3) Run
After clicking download, you can find that the browser will download the logo Jpg this file.
epilogue
The above is the upload and download of files sorted out by Xinyi students according to reading the big guy's articles on the Internet. File upload and download are also more important in our development, because we often need to upload corresponding files to a website or download corresponding resources from a website, which requires the use of file upload and download technology.