Previously wrote a STRUTS2 implementation of the file upload, this blog post is mainly to summarize the next SPRINGMVC implementation of file upload Steps. First take a look at the individual file upload, and then summarize the next multiple file uploads.
1. Environmental Preparedness
SPRINGMVC the ability to upload a file requires two Jar package support http://download.csdn.net/detail/eson_15/9556808, as follows
2. Uploading of individual files
2.1 Front Page
Simply write the foreground page and note that the form does not forget to write the enctype="multipart/form-data"
property:
<TR> <TD>Product pictures</TD> <TD><c:ifTest= "${itemscustom.pic!=null}"> <imgsrc= "/file/${itemscustom.pic}"width=100Height=100/><BR/> </c:if> <inputtype= "file"name= "items_pic"/> </TD></TR>
2.2 Multipart parsing of multi-component types
This means that for the above enctype="multipart/form-data"
type, SPRINGMVC needs to parse the multipart type of data and configure the multipart type resolver in Springmvc.xml.
<!--file upload, need to configure Multipartresolver processor -<BeanID= "multipartresolver"class= "org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--set the maximum size of the file on board to 5MB - < propertyname= "maxuploadsize"value= "5242880"/> < propertyname= "defaultencoding"value= "utf-8"/> </Bean>
2.3 Creating a file saved virtual directory
Before uploading a file, the first to create a virtual directory to save the file, the virtual directory will correspond to an actual directory on the disk, in practice there will be a server dedicated to storage resources, here we use local to save the file, and then map a virtual directory, Used to specify the path to get the file in the program (in fact, in the foreground page above, the src= "/file/${itemscustom.pic}" in The/file is the virtual directory).
There are two ways to create one: double-click the Tomcat server in myeclipse, and then pop up the following box:
After setting up, save, so that the uploaded files will be saved to the directory specified in the document base, equivalent to the virtual map to the directory specified by path, the program to get this file, to be obtained from the virtual directory specified by path, that is, i/file Above.
The second method is configured in the Tomcat configuration file, in fact, just in the myeclipse operation has been automatically written to this configuration file, the configuration file location in the Tomcat directory/conf/server.xml, look inside there will be more than one line:
This is just what I configured, it is automatically written to this file, so we can also directly in the file to write, it does not need to be configured in the Myeclipse.
2.4 Writing the backend controller method
Next is the focus, the Front-desk file, we need to handle in the controller, and then saved to disk, but also mapped to our configured virtual path, then how to receive it? Look at the following code:
@RequestMapping ("/edititemssubmit") publicString edititemssubmit (model, httpservletrequest request, Integer id, @Validated (value
= {ValidGroup1.class}) itemscustom itemscustom, bindingresult bindingresult, @RequestParam multipartfile[] items_p Ic)throwsException {//Get the checksum error message if(bindingresult.haserrors ()) {//Output error messageList<objecterror> allerrors =bindingresult.getallerrors (); for(objecterror Objecterror:allerrors) {//System.out.println (objecterror.getdefaultmessage ()); //the Original is the above sentence, but because the properties file default cannot input chinese, so I changed the properties file to Utf-8 code,//But such words read out is garbled, so I first use ISO scrambled, and then use Utf-8 generation, can solve garbled problemSystem.out.println (NewString (objecterror.getdefaultmessage (). getBytes ("iso-8859-1"), "UTF-8")); } //upload error message to pageModel.addattribute ("allerrors", allerrors); } /* Processing an uploaded single picture//original name String originalfilename = Items_pic.getoriginalfilename (); Upload picture if (items_pic! = null && originalfilename! = null && originalfilename.length () > 0) { The physical path of the stored picture String Pic_path = "e:\\github\\develop\\upload\\temp\\"; New picture name String NewFileName = uuid.randomuuid () + originalfilename.substring (originalfilena Me. LastIndexOf (".")); New image File NewFile = new file (pic_path + newfilename); Writes the in-memory data to disk Items_pic.transferto (newFile); Write the name of the new picture into the Itemscustom itemscustom.setpic (newfilename); } else {//if the user has not selected a picture to upload, also with the original picture Itemscustom temp = Itemsservice.finditemsbyid (itemscustom.getid ()) ; Itemscustom.setpic (temp.getpic ()); }//call Service to update the product information, the page needs to upload the product information to this method Itemsservice.updateitems (id, Itemscustom); */ //return "redirect:queryItems.action"; //return "forward:queryItems.action"; return"/web-inf/jsp/success.jsp"; }
First look at the formal parameters, mainly Itemscustom and multipartfile type of items_pic, I upload a picture here is a property of the Itemscustom class, so with this parameter, is to write to the class, In addition to the previous @validated note is I write SPRINGMVC check when used, and here file upload Irrelevant. The Springmvc file upload class is multipartfile, and the name items_pic must match the foreground name Property.
The logic of uploading the file is to first determine if there is no upload file, if uploaded, then rename the file and write it to Disk. If you do not upload the file, then I should still use the original file (image), because I wrote this example is to update the product information, the file upload there is no non-null validation, so wrote here Else.
So the file is uploaded, this is a single file Upload. But some problems will be error, and later commented out using multiple file Upload.
3. Uploading multiple files
Multiple file uploads and a single file upload the same principle, but in the details will be a little different, to me a summary. The first thing to note on the foreground page is that the name attribute must be the same, namely:
@RequestMapping ("/edititemssubmit") publicString edititemssubmit (model, httpservletrequest request, Integer id, @Validated (value
= {ValidGroup1.class}) itemscustom itemscustom, bindingresult bindingresult, @RequestParam multipartfile[] items_p Ic)throwsException {//Get the checksum error message if(bindingresult.haserrors ()) {//Output error messageList<objecterror> allerrors =bindingresult.getallerrors (); for(objecterror Objecterror:allerrors) {//System.out.println (objecterror.getdefaultmessage ()); //the Original is the above sentence, but because the properties file default cannot input chinese, so I changed the properties file to Utf-8 code,//But such words read out is garbled, so I first use ISO scrambled, and then use Utf-8 generation, can solve garbled problemSystem.out.println (NewString (objecterror.getdefaultmessage (). getBytes ("iso-8859-1"), "UTF-8")); } //upload error message to pageModel.addattribute ("allerrors", allerrors); } //multiple file uploads//multiple pictures, do not save the database, print a bit here for(multipartfile Myfile:items_pic) {if(myfile.isempty ()) {System.out.println ("file not uploaded"); }Else{System.out.println ("file length:" +myfile.getsize ()); System.out.println ("file type:" +Myfile.getcontenttype ()); System.out.println ("file name:" +Myfile.getname ()); System.out.println ("file formerly known as:" +Myfile.getoriginalfilename ()); System.out.println ("========================"); String OriginalFilename=Myfile.getoriginalfilename (); String Pic_path= "e:\\github\\develop\\upload\\temp\\"; String NewFileName=uuid.randomuuid () +originalfilename.substring (originalfilename.lastindexof ("."))); File NewFile=NewFile (pic_path +newfilename); Myfile.transferto (newFile); } } /* Processing an uploaded single picture//original name String originalfilename = Items_pic.getoriginalfilename (); Upload picture if (items_pic! = null && originalfilename! = null && originalfilename.length () > 0) { The physical path of the stored picture String Pic_path = "e:\\github\\develop\\upload\\temp\\"; New picture name String NewFileName = uuid.randomuuid () + originalfilename.substring (originalfilena Me. LastIndexOf (".")); New image File NewFile = new file (pic_path + newfilename); Writes the in-memory data to disk Items_pic.transferto (newFile); Write the name of the new picture into the Itemscustom itemscustom.setpic (newfilename); } else {//if the user has not selected a picture to upload, also with the original picture Itemscustom temp = Itemsservice.finditemsbyid (itemscustom.getid ()) ; Itemscustom.setpic (temp.getpic ()); }//call Service to update the product information, the page needs to upload the product information to this method Itemsservice.updateitems (id, Itemscustom); */ //return "redirect:queryItems.action"; //return "forward:queryItems.action"; return"/web-inf/jsp/success.jsp"; }
As above, the parameter becomes an array type, and the @requestparam annotation is preceded by the LINE. And then, it is to iterate over the array, which is exactly the same as uploading the individual files inside the Loop. Look at the print results:
Http://localhost:8080/SpringMVC_Study/editItems.action?id=3
You can see that two files have been successfully received, to this point, the Multi-file upload success. The file upload function about SPRINGMVC is summarized Here.
This article has encountered some problems have been prompted the non-mapped characters of the encoded UTF-8, plus the following code, do not work
<Build><Plugins><plugin> <groupId>Org.apache.maven.plugins</groupId> <Artifactid>Maven-compiler-plugin</Artifactid> <version>2.1</version> <Configuration> <Skip>True</Skip> <Source>1.6</Source> <Target>1.6</Target> <!--<source>${java.compiler}</source> <target>${java.compiler}</target> - <encoding>UTF-8</encoding> </Configuration> </plugin></Plugins> </Build><Properties><project.build.sourceEncoding>Utf-8</project.build.sourceEncoding> </Properties>
The final discovery is that the Java Compiler version has installed the JRE version issue
"SPRINGMVC Learning 08" springmvc implement file Upload