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):
<!--default MVC annotation Mapping Support--<mvc:annotation-driven/> <!--handling requests for static resources--<mvc:resources location= "/sta tic/"mapping="/static/** "/> <!--scan annotations--<context:component-scan base-package=" Com.ztz.springmvc.controller "/> <!--View Resolver--<bean class=" Org.springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" viewclass "value=" Org.s Pringframework.web.servlet.view.JstlView "/> <!--prefix--<property name=" prefix "value="/web-inf/jsp /"/> <!--suffix-<property name=" suffix "value=". jsp "/> </bean> <!--uploading Files--<bean I D= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" > < Property Name= "Defaultencoding" value= "Utf-8"/> <!--max memory size-<property name= "maxinmemorysize" value= "10 "/> <!--maximum file size, 1 for unlimited size and <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;
Omitting the Get Set method
//overriding toString () facilitates testing
@Override public
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 ());
Get 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 judge if not picture, prohibit upload) String contenttype=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 the @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 upload
SPRINGMVC 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> Username: </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 ());
Get 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 (). Re
Placeall ("-", "" ");
Get file type (can judge if not picture, prohibit upload) String contenttype=mf.getcontenttype ();
Get the file suffix name String imagename=contenttype.substring (Contenttype.indexof ("/") +1); Path= "/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 the @RequestMapping (value= "/forward") private String Forward () {return "index";
}
}
PS: This demo address: http://download.csdn.net/detail/zwz568017880/9043089