The implementation of the upload image function is well implemented in SPRINGMVC. Now I'll show you a complete example.
There are several jars that need to be added to the Pom.xml, respectively:
<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>
Next, add the configuration of the upload file to the SPRINGMVC configuration (PS: I show the full configuration of SPRINGMVC):
<!--The default MVC annotation map support--><mvc:annotation-driven/><!--handle requests for static resources--><mvc:resources location= "/ static/"mapping="/static/** "/><!--scan annotations--><context:component-scan base-package=" Com.ztz.springmvc.controller "/><!--View parser--><bean class=" Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" Viewclass "value=" Org.springframework.web.servlet.view.JstlView "/> <!--prefix--><property name=" prefix "value="/ web-inf/jsp/"/><!--suffix--><property name=" suffix "value=". jsp "/></bean><!--upload file-->< Bean id= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >< Property Name= "Defaultencoding" value= "utf-8"/><!--maximum memory size--><property name= "maxinmemorysize" value= " 10240 "/><!--maximum file size, 1 for unrestricted size--><property name=" maxuploadsize "value="-1 "/></bean>
One, single file upload
Of course, in a form, you need to add enctype= "Multipart/form-data", a form has a file field, there must be a basic text box, can be submitted one time, SPRINGMVC can give us a difference, to do different processing. First look at the normal model
Package Com.ztz.springmvc.model;public class Users {private string Name;private string password;//omit Get Set method// Rewrite ToString () to conveniently test @overridepublic String ToString () {return "Users [name=" + name + ", password=" + password + "]";}}
This is the JSP page for the form:
<%@ page language= "java" contenttype= "text/html; charset=utf-8" pageencoding= " Utf-8 "%><% @taglib prefix=" C "uri=" http://java.sun.com/jstl/core_rt "%><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; Request.setattribute ("BasePath", basepath);%><! DOCTYPE html><%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%><% @taglib prefix=" C "uri=" Http://java.sun.com/jstl/core_rt "%><% String path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; Request.setattribute ("BasePath", basepath);%><! DOCTYPE html>
And finally the controller:
Package Com.ztz.springmvc.controller;import Java.io.file;import Java.util.uuid;import Javax.servlet.http.httpservletrequest;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 com.ztz.springmvc.model.Users; @Controller @requestmapping ("/file") public class Fileuploadcontroller {@ Requestmapping (value= "/upload", method=requestmethod.post) Private String fildupload (Users users, @RequestParam ( value= "File", Required=false) multipartfile file,httpservletrequest request) throws exception{// Basic Form System.out.println (users.tostring ());//Gets the physical path WebApp the path where string pathroot = Request.getsession (). Getservletcontext (). Getrealpath (""); String Path= "", if (!file.isempty ()) {//generates UUID as file name string uuid = Uuid.randomuuid (). toString (). ReplaceAll ("-", "" ");// Get file type (can be judged if not picture, no upload) StringContenttype=file.getcontenttype ();//Get the file suffix name string imagename=contenttype.substring (Contenttype.indexof ("/") +1); Path= "/static/images/" +uuid+ "." +imagename;file.transferto (new file (Pathroot+path));} SYSTEM.OUT.PRINTLN (path); Request.setattribute ("Imagespath", path); return "Success";} Because my JSP under the Web-inf directory, the browser cannot directly access @requestmapping (value= "/forward") private String Forward () {return "index";}}
Click Submit Console output:
Users [Name=fileupload, Password=test]
The browser displays the results:
second, multi-image uploadSPRINGMVC implementation of multi-image upload is also very simple, we have just modified the example, in addition to a file field, the value of name is the same
<body><form action= "${basepath}file/upload" method= "post" enctype= "Multipart/form-data" ><label> User name: </label><input type= "text" name= "name"/><br/><label> Password: </label><input type= " Password "name=" password "/><br/><label> avatar 1</label><input type=" file "name=" file "/>< br/><label> Avatar 2</label><input type= "file" name= "file"/><br/><input type= "Submit" Value= " /></form></body>"
Show pictures in a loop so that you can display more than one picture<body><c:foreach items= "${imagespathlist}" var= "image" ><br/ ></c:forEach></body>
The control layer code is as follows:Package Com.ztz.springmvc.controller;import Java.io.file;import Java.util.arraylist;import java.util.List;import Java.util.uuid;import Javax.servlet.http.httpservletrequest;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 com.ztz.springmvc.model.Users; @Controller @requestmapping ("/file") public class Fileuploadcontroller {@ Requestmapping (value= "/upload", method=requestmethod.post) Private String fildupload (Users users, @RequestParam ( value= "File", Required=false) multipartfile[] file,httpservletrequest request) throws exception{// Basic Form System.out.println (users.tostring ());//Gets the physical path WebApp the path where string pathroot = Request.getsession (). Getservletcontext (). Getrealpath (""); String path= ""; List<string> listimagepath=new arraylist<string> (); for (MultipartFile mf:file) {if (!mf.isempty ()) {//generates UUID as file name string uuid = Uuid.randomuuid (). toString (). ReplaceAll ("-", "");// Get file type (can be judged if not picture, prohibit upload) string contenttype=mf.getcontenttype ();//Get file suffix name string imagename=contenttype.substring ( Contenttype.indexof ("/") +1);p ath= "/static/images/" +uuid+ "." +imagename;mf.transferto (New File (Pathroot+path)); Listimagepath.add (path);}} SYSTEM.OUT.PRINTLN (path); Request.setattribute ("Imagespathlist", Listimagepath); return "Success";} Because my JSP under the Web-inf directory, the browser cannot directly access @requestmapping (value= "/forward") private String Forward () {return "index";}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Springmvc upload pictures and display pictures--support multi-image upload