The file upload and download functions have been used in recent projects. I think this function is more important, so I specially extracted it and tried it myself.
The following are the specific steps for uploading and downloading files in springMVC configuration environment for your reference. The specific content is as follows
1. Basic configuration:
Maven import package and configuration pom.xml. In addition to the basic dependencies of springmvc, it is necessary to import commons-io.jsr and commons-fileupload.jar used when uploading files:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>filLoadTest</groupId> <artifactId>filLoadTest</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>filLoadTest Maven Webapp</name> <url>http://maven.apache.org</url> <build> <finalName>filLoadTest</finalName> <plugins> <!-- The following configuration can ensure that the jre version will not change every time the forced update is, then my eclipse4.4.1 and maven3.2.5 are examples. If you do not set this, jre will change back to 1.5 every time the forced update is forced --> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> <compilerArguments> <verbose /> <bootclasspath>${java.home}/lib/rt.jar</bootclasspath> </compilerArguments> </configuration> </plugin> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.6.RELEASE</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> </dependencies> </project>Basic configuration of web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <filter> <description>charset filter</description> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <description>charset encoding</description> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
Spring basic configuration spring.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:annotation-config /> <mvc:annotation-driven /> <context:component-scan base-package="controllers" /> <!-- To avoid download files from returning to JSON when IE executes AJAX --> <bean id="mappingJacksonHttpMessageConverter" > <property name="supportedMediaTypes"> <list> <value>text/html;charset=utf-8</value> </list> </property> </bean> <!-- To enable Spring MVC annotation function to complete the mapping of requests and annotations POJOs --> <bean > <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /><!-- json converter--> </list> </property> </bean> <!-- Support upload of files--> <bean id="multipartResolver" > <!-- 100M --> <property name="maxUploadSize" value="104857600"></property> <property name="defaultEncoding" value="utf-8"></property> </bean> </beans>
2. File upload code
For the uploaded simple page index.html, pay attention to the settings of the entype when submitting the form form:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <form action="./upLoadFile.do" method="post" enctype="multipart/form-data"> Select file: <input type="file" name="file"/> <input type="submit" value="submit"/> </form> </body> </html>
Upload the corresponding background java code. For specific questions, please refer to the comments:
package controllers; import java.io.File; import java.io.IOException; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; @Controller public class fileController { /** * File upload* * @author: tuzongxun * @Title: upLoadFile * @param @param file * @param @param request * @param @throws IllegalStateException * @param @throws IOException * @return void * @date Apr 28, 2016 1:22:00 PM * @throws */ @RequestMapping(value = "/upLoadFile.do", method = RequestMethod.POST) public void upLoadFile(HttpServletRequest request) throws IllegalStateException, IOException { // @RequestParam("file") MultipartFile file, CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); // Determine whether the request has file upload, that is, if (multipartResolver.isMultipart(request)) { // Convert to multipart request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // Get all file names in the request Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { // Get uploaded file MultipartFile f = multiRequest.getFile(iter.next()); if (f != null) { // Get the file name of the currently uploaded file String myFileName = f.getOriginalFilename(); // If the name is not "", it means that the file exists, otherwise it means that the file does not exist if (myFileName.trim() != "") { // Define the upload path String path = "C://Users//tuzongxun123//Desktop//" + myFileName; File localFile = new File(path); f.transferTo(localFile); } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } } }After selecting the file to submit, you will see that the selected file is passed to the specified location in the code. The page rendering is as follows
3. File download
File download requires the storage path of the downloaded file. This is just manually filled in. If it is in a specific project, you can save the file name and uploaded storage path in the database. Then add a page of the file list to display the file name and file path, and then click to upload the corresponding file name and path to the background operation when downloading.
/** * File download, file name and file address required* * @author: tuzongxun * @Title: download * @param@param name * @param@param path * @param@return * @param@throws IOException * @returnResponseEntity<byte[]> * @date Apr 28,2016 1:21:32 PM * @throws */ @RequestMapping(value = "/downLoadFile.do") public ResponseEntity<byte[]> download(@RequestParam("name") String name, @RequestParam("filePath") String path) throws IOException { File file = new File(path); HttpHeaders headers = new HttpHeaders(); String fileName = new String(name.getBytes("UTF-8"), "iso-8859-1");// In order to solve the problem of garbled Chinese names headers.setContentDispositionFormData("attachment", fileName); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); } The Html page is just a simple fill in the file name and file path, and submit it to the background using the form form. Then the background will control the response to the selection box for saving the file path popup on the page. Of course, I did not do anything in the background here. If the file does not exist, an error will be reported. You can perform corresponding processing:
File download:
</br> </br> <form action="./downLoadFile.do"style="border:1px solid grey;width:auto;" method="post"> File name: <input type="text" name="name"/></br></br> File path: <input type="text" name="filePath"/></br></br> <input type="submit" value="Confirm download"/> </form>
The page view is as follows:
If the file does not exist, the error is as follows:
The above is all about this article, I hope it will be helpful to everyone's learning.