Just look at the code, the comments are all inside
First of all, web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>Configure the front-end controller of SpringMVC</description> <servlet-name>upload</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>upload</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <description>Solve garbled problems in parameter delivery</description> <filter-name>CharacterEncodingUTF8</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingUTF8</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
Below is located at //src//applicationContext.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!-- Start Spring's component automatic scanning mechanism (Spring will automatically scan the classes and subpackages specified by base-package) --> <!-- Here you can refer to my article http://blog.csdn.net/jadyer/article/details/6038604 --> <context:component-scan base-package="com.jadyer"/> <!-- Start SpringMVC annotation function, it will automatically register related instances of HandlerMapping, HandlerAdapter, and ExceptionResolver --> <mvc:annotation-driven/> <!-- Since SpringMVC is set in web.xml to intercept all requests, it will not be read when reading static resource files --> <!-- Through this configuration, you can specify all resources that request or reference "/js/**" and will be found from "/js/" --> <mvc:resources mapping="/js/**" location="/js/"/> <mvc:resources mapping="/upload/**" location="/upload/"/> <!-- When uploading files by SpringMVC, you need to configure the MultipartResolver processor-> <bean id="multipartResolver"> <!-- Specify that the total size of the uploaded files cannot exceed 800KB... Note that the limit of the maxUploadSize property is not for a single file, but for the sum of the capacity of all files--> <property name="maxUploadSize" value="800000"/> </bean> <!-- When SpringMVC exceeds the upload file limit, it will throw org.springframework.web.multipart.MaxUploadSizeExceededException --> <!-- This exception was thrown by SpringMVC when checking uploaded file information, and it has not entered the Controller method at this time --> <bean id="exceptionResolver"> <property name="exceptionMappings"> <props> <!-- When encountering a MaxUploadSizeExceededException exception, it will automatically jump to /WEB-INF/jsp/error_fileupload.jsp--> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop> </props> </property> </bean> <bean> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean></beans>
The following is the prompt page when uploading the file content is too large //WEB-INF//jsp//error_fileupload.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<h1>The file is too large, please reselect</h1>
Below is the upload page for selecting files index.jsp
<%@ page language="java" pageEncoding="UTF-8"%><!-- This cannot be abbreviated as <script type="text/javascript" src=".."//js/jquery-1.10.2.min.js"></script><script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script><script type="text/javascript" src="<%=request.getContextPath()%>/js/ajaxfileupload.js"></script><script type="text/javascript">function ajaxFileUpload(){ //A picture is displayed when uploading a file, and the file upload is completed to hide the picture //$("#loading").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();}); //The function $.ajaxFileUpload({ //The server address of the file upload operation (the parameters can be passed, and it has been tested personally) url:'${pageContext.request.contextPath}/test/fileUpload?uname=Xuanyu', secureuri:false, //Whether secure commit is enabled, the default is false fileElementId:'myBlogImage', //The id attribute dataType:'text', //The format returned by the server can be json or xml, etc. success:function(data, status){ //The processing function data = data.replace("<PRE>", ''); //ajaxFileUpload will add the suffix of <pre>text</pre> to the text content that the server responds back to. data = data.replace("</PRE>", ''); data = data.replace("<pre>", ''); data = data.replace("</pre>", ''); data = data.replace("</pre>", ''); //In this example, after the upload file is completed, the server will return to the foreground [0`filepath] if(data.substring(0, 1) == 0){ //0 means uploading successfully (superhes the file path after upload), 1 means failure (superhes the failure description) $("img[id='uploadImage']").attr("src", data.substring(2)); $('#result').html("Image upload successfully<br/>"); }else{ $('#result').html('Image upload failed, please try again! ! '); } }, error:function(data, status, e){ //The processing function $('#result').html('Image upload failed, please try again!!'); } });}</script><div id="result"></div><img id="uploadImage" src="http://www.firefox.com.cn/favicon.ico"><input type="file" id="myBlogImage" name="myfiles"/><input type="button" value="upload image" onclick="ajaxFileUpload()"/><!-- Introduction to AjaxFileUpload Official website: http://phpletter.com/Our-Projects/AjaxFileUpload/Introduction: jQuery plug-in AjaxFileUpload can achieve refresh-free uploading files, and is simple and easy to use. It has a lot of users. It is very worth recommending: the order of introducing js (it depends on jQuery) and there are no forms in the page (it only triggers the ajaxFileUpload() method when the button is clicked) Common errors and solutions are as follows 1) SyntaxError: missing ; before statement -- check whether the URL path can be accessed 2) SyntaxError: syntax error -- check whether the JSP file that handles the submission operation has syntax error 3) SyntaxError: invalid property id --check whether the property ID exists 4)SyntaxError: missing } in XML expression --check whether the file domain name is consistent or not 5) Other custom errors --check whether the parameters are correct by directly printing the variable $error, which is much more convenient than the above invalid error prompts --> Finally, FileUploadController.java that handles file upload
package com.jadyer.controller;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.io.FileUtils;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;/** * File upload in SpringMVC* 1) Since SpringMVC uses commons-fileupload implementation, it must first introduce its components into the project* 2) Configure the MultipartResolver processor in the SpringMVC configuration file (the attribute restrictions on uploaded files can be added here) * 3) Add the MultipartFile parameter to the Controller method (this parameter is used to receive the content of the file component in the form) * 4) Write the foreground form (note enctype="multipart/form-data" and <input type="file" name="****"/>) * PS: Since ajaxfileupload.js is used here to achieve refresh-free upload, the form is not used in this example* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- spring-context-3.2.4.RELEASE.jar * spring-core-3.2.4.RELEASE.jar * spring-expression-3.2.4.RELEASE.jar * spring-jdbc-3.2.4.RELEASE.jar * spring-oxm-3.2.4.RELEASE.jar * spring-tx-3.2.4.RELEASE.jar * spring-web-3.2.4.RELEASE.jar * spring-web-3.2.4.RELEASE.jar * spring-web-3.2.4.RELEASE.jar * spring-webmvc-3.2.4.RELEASE.jar * -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- After uploading the file, return to the foreground [0`filepath], 0 means uploading successfully (sequent to the uploaded file path), 1 means failure (sequent to the failure description) */ @RequestMapping(value="/fileUpload") public String addUser(@RequestParam("uname") String uname, @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException{ //You can receive other parameters while uploading the file System.out.println("Received user[" + uname + "] file upload request"); //If you are using the Tomcat server, the file will be uploaded to //%TOMCAT_HOME%//webapps//YourWebProject//upload//Folder//The commons.io.FileUtils class is used to implement file upload operations here. It will automatically determine whether /upload exists. If it does not exist, it will automatically create String realPath = request.getSession().getServletContext().getRealPath("/upload"); //Set the data format response to the foreground content response.setContentType("text/plain; charset=UTF-8"); //Set the PrintWriter object that responds to the foreground content PrintWriter out = response.getWriter(); //The original name of the upload file (that is, the file name before uploading) String originalFilename = null; //If you just upload one file, you only need to receive the file in MultipartFile type, and there is no need to explicitly specify the @RequestParam annotation//If you want to upload multiple files, you need to use the MultipartFile[] type to receive the file, and specify the @RequestParam annotation//When uploading multiple files, all the names of <input type="file"/> in the front desk form should be myfiles, otherwise the myfiles in the parameter cannot obtain all uploaded files for(MultipartFile myfile : myfiles){ if(myfile.isEmpty()){ out.print("1`Please select the file and upload it"); out.flush(); return null; }else{ originalFilename = myfile.getOriginalFilename(); System.out.println("File original name: " + originalFilename); System.out.println("File name: " + myfile.getName()); System.out.println("File length: " + myfile.getSize()); System.out.println("File type: " + myfile.getContentType()); System.out.println("======================================================================================================== System.out.println("===================================================================================================================================================================================================================================================================================================================================================================================================== { System.out.println("File[" + originalFilename + "] upload failed, the stack track is as follows"); e.printStackTrace(); out.print("1` file upload failed, please try again! ! "); out.flush(); return null; } } } //The output in Windows is [D:/Develop/apache-tomcat-6.0.36/webapps/AjaxFileUpload//upload/Anger Birds.jpg] //System.out.println(realPath + "//" + originalFilename); //The output in Windows is [/AjaxFileUpload/upload/Anger Birds.jpg] //System.out.println(request.getContextPath() + "/upload/" + originalFilename); //Recommendation of [realPath + "//" + originalFilename] is not recommended // because <img src="file:////D:/aa.jpg"> can be displayed by firefox under Windows, and <img src="D:/aa.jpg">firefox is unrecognized out.print("0`" + request.getContextPath() + "/upload/" + originalFilename); out.flush(); return null; }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.