File upload is an important function point in web development. Similarly, the SPRINGMVC can be easily configured to upload files and upload files to the processing. The steps are as follows:
A new test project and import jar package
The detailed process does not say much, the project structure and the required jar packages are as follows:
650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7F/FA/wKioL1czUcugStDUAABcOr_ekYE451.png "title=" 20160426114208_20198.png "alt=" wkiol1czucugstduaabcor_ekye451.png "/> 650" this.width=650; "src=" http:// S5.51cto.com/wyfs02/m02/7f/fd/wkiom1czupmx247vaaajantdskm217.png "title=" 20160426114231_65490.png "alt=" Wkiom1czupmx247vaaajantdskm217.png "/>
General configuration of the second project and the configuration required to implement the upload
(1) Web. xml:
<web-app xmlns= "Http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/ Web-app_3_1.xsd " version=" 3.1 "><servlet>< Servlet-name>springmvc</servlet-name><servlet-class> org.springframework.web.servlet.dispatcherservlet</servlet-class><load-on-startup>1</ Load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name> <url-pattern>*.html</url-pattern></servlet-mapping><filter><filter-name> Characterencodingfilter</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>characterencodingfilter</filter-name><url-pattern>/*</url-pattern></ Filter-mapping></web-app>
(2) Springmvc-servlet.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: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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd " ><context:component-scan base-packagE= "Cn.zifangsky.* *.controller" /><context:annotation-config /> <!-- annotations defined in the activation bean --><mvc:annotation-driven /><!-- View-related configuration --><beanclass = "Org.springframework.web.servlet.view.InternalResourceViewResolver" ><property name= "prefix" Value= "/web-inf/pages/" /> <!-- View prefix --><property name= "suffix" value= ". jsp" /> <!-- view suffix --></bean><bean id= " Multipartresolver " class=" Org.springframework.web.multipart.commons.CommonsMultipartResolver ">< Property name= "Uploadtempdir" value= "/tmp" /> <!-- Temp directory -->< Property name= "Maxuploadsize" value= "10485760"/> <!-- 10M --></bean> </beans>
In the last paragraph of the above code, a bean named "multipartresolver" is configured, which is configured with Commons fileupload to handle file uploads
Three-file upload processing process
(1) Home index.jsp:
<% response.sendredirect ("form.html"); %>
(2) Model class User.java:
Package Cn.zifangsky.model;public class User {private string userName;//user name private string logosrc;//avatar Address public string GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String getlogosrc () {return logosrc;} public void Setlogosrc (String logosrc) {this.logosrc = logosrc;}}
(3) file upload form and Results display page fileupload.jsp:
<%@ page language= "java" contenttype= "Text/html; charset=utf-8" pageEncoding= "UTF-8"% ><% @taglib prefix= "MVC" uri= "Http://www.springframework.org/tags/form"%><% @taglib Prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>As you can see, the file upload form is defined in the form form above, and in order to be able to upload the file, a enctype= "multipart/form-data" attribute is added. The following is the result display page, using the JSTL tag to determine whether there is a result, and some words will show
(4) Background processing Uploadcontroller.java:
package cn.zifangsky.controller;import java.io.file;import java.io.ioexception;import javax.servlet.http.httpservletrequest;import org.apache.commons.io.fileutils;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.servlet.modelandview; import cn.zifangsky.model.user;import cn.zifangsky.utils.stringutile; @Controllerpublic class uploadcontroller {@RequestMapping (value = "/form") Public modelandview form () {modelandview modelandview = new modelandview ("FileUpload", "user", new user ()); Return modelandview;} @RequestMapping (value = "/upload", method = requestmethod. POST) Public modelandview upload (user user, @RequestParam ("file") MultipartFile Tmpfile, httpservletrequest request) {ModelAndView modelAndView = new Modelandview ("FileUpload");if (tmpfile != null) {// Get physical path string targetdirectory = request.getsession (). Getservletcontext (). Getrealpath ("/uploads"); String tmpfilename = tmpfile.getoriginalfilename (); // uploaded file name int dot = tmpfilename.lastindexof ('. '); string ext = ""; //file suffix if (dot > -1) && (dot < (Tmpfilename.length () - 1)) {ext = tmpfilename.substring (dot + &NBSP;1);} Other file formats do not process if ("PNG". Equalsignorecase (EXT) | | "JPG". Equalsignorecase (EXT) | | "GIF". Equalsignorecase (EXT)) {// Rename the uploaded file name string targetfilename = Stringutile.renamefilename (TmpfIlename);// Save the new file File target = new file (targetdirectory, targetfilename); try {// Save File Fileutils.copyinputstreamtofile (Tmpfile.getinputstream (), target);} catch (ioexception e) {e.printstacktrace ();} User u = new user (); U.setusername (User.getusername ()); U.setlogosrc (Request.getContextPath ( ) + "/uploads/" + targetfilename); Modelandview.addobject ("U", u);} Return modelandview;} Return modelandview;}} multipartfile
/** * file renamed */public static string Renamefilename (String fileName) {string formatdate = new SimpleDateFormat ("Yymmddhhmmss "). Format (new Date ()); Current time string int random = new Random (). Nextint (10000); String extension = filename.substring (Filename.lastindexof (".")); File suffix return formatdate + random + extension;}
At this point, all processing logic has been completed.
Four-effect test
(1) File Upload form:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/7F/FA/wKioL1czUnnCoqOJAAAm1WoJkvo269.png "title=" 20160426120933_39151.png "alt=" Wkiol1czunncoqojaaam1wojkvo269.png "/>
(2) Upload result:
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/7F/FA/wKioL1czUpGSActAAAA_-proDt0609.png "title=" 20160426120951_80300.png "alt=" Wkiol1czupgsactaaaa_-prodt0609.png "/>
This article is from "Zifangsky's personal blog" blog, make sure to keep this source http://983836259.blog.51cto.com/7311475/1772440
Springmvc implementing file Uploads