SPRINGMVC Series (iv) annotated way to upload files

Source: Internet
Author: User
Tags tomcat server

This article mainly introduces two ways to upload files Springmvc

The second is the first, using the parser, greatly improving the efficiency of the upload.

The first type:

Steps:

1. Introduction of JAR Package

2. Configuring the Spring-servlet.xml File

   <!--Springmvc Upload a file, you need to configure the Multipartresolver processor--<bean id= "Multipartresolver" class= "org.springframework.          Web.multipart.commons.CommonsMultipartResolver "> <property name=" defaultencoding "value=" UTF-8 "/> <!--Specifies that the total size of the uploaded file cannot exceed 200KB. Note that the limit for the Maxuploadsize property is not for individual files, but for all files, and <property name= "maxuploadsize" value= "200000"/> &L T;property name= "defaultencoding" value= "Utf-8"/> <property name= "maxinmemorysize" value= "40960 "/> </bean> <!--Springmvc will be thrown when the upload file limit is exceeded Org.springframework.web.multipart.MaxUploadSizeExceed Edexception-<!--This exception was thrown when Springmvc checked for uploaded file information and was not yet in the Controller method--<bean id= "Exceptionres Olver "class=" Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver "> <property name=" exce Ptionmappings "> <props> <!--automatically jumps to/w when a Maxuploadsizeexceededexception exception is encounteredEb-inf/jsp/error_fileupload.jsp page--<prop key= "Org.springframework.web.multipart.MaxUploadSizeExc  Eededexception ">error_fileupload</prop> </props> </property> </bean>


3. Write JSP

File Upload method, you must use post!

Set the encoding for the form and must be Enctype= "Multipart/form-data" >

4. Write Controller

Using the SPRINGMVC package to upload files, annotated way to get the files in the JSP. (@RequestParam ("filename")

@Controller @requestmapping ("/file") public class Index {@RequestMapping (value = "/upload1") public String AddUser (@ Requestparam ("filename") commonsmultipartfile file,httpservletrequest request) throws IOException {if (!file.isempty ( ) {try {//get the output stream, rename the uploaded file FileOutputStream os = new FileOutputStream ("d:/" + New Date (). GetTime () + file.getoriginalfile Name ());//Gets the input stream of the uploaded file InputStream in = File.getinputstream ();//writes the file as a write section int b = 0;while ((b = In.read ())! =-1) {Os.write (b);} Os.flush (); Os.close (); In.close ();} catch (FileNotFoundException e) {e.printstacktrace ();}} Return "Success";}

The second type: optimized upload file

Idea: Using the parser, greatly improve the upload speed

The difference from method one is only the controller

@RequestMapping ("/upload2") public String upload2 (httpservletrequest request, httpservletresponse response) throws IllegalStateException, IOException {//Create a generic multipart parser to parse the SPRINGMVC context commonsmultipartresolver Multipartresolver = New Commonsmultipartresolver (Request.getsession (). Getservletcontext ());//Parse request to determine if the data is Multipartfile type, That is, multi-part Request if (Multipartresolver.ismultipart (Request)) {//Convert to multipart requestmultiparthttpservletrequest multirequest = ( Multiparthttpservletrequest) request;//obtains all the file names in the request iterator<string> iter = Multirequest.getfilenames (); while (Iter.hasnext ()) {//Get upload file multipartfile filename = multirequest.getfile (Iter.next ()), if (file! = null) {//Get the file currently uploaded Name string myfilename = File.getoriginalfilename ();//If the name is not "", the file exists, otherwise the file does not exist if (Myfilename.trim ()! = "") {//  Rename the uploaded file name string filename = new Date (). GetTime () + file.getoriginalfilename ();/* *//define upload path string path = "h:/" + fileName; FILE * LocalFile = new file (path); * Copy the file to Local: TransferTo (gest) writes the upload file to the server specified file *File.transferto (LocalFile); *///If you are using a TOMCAT server, the files are uploaded to the \\%tomcat_home%\\webapps\\yourwebproject\\web-inf\\upload\\ folder in string Realpath = Request.getsession (). Getservletcontext (). Getrealpath ("/web-inf/upload");//do not have to deal with the IO stream shutdown problem, Because the Fileutils.copyinputstreamtofile () method internally automatically switches the IO stream used to Fileutils.copyinputstreamtofile (File.getinputstream (), New File (Realpath, FileName));}}} return "/success"; <span style= "Font-family:microsoft Yahei;" >}</span>


Summarize:

This article mainly introduces two ways of Springmvc uploading files. Use SPRINGMVC to upload the file encapsulation method, do upload operation.

The second is the first, using the parser, greatly improving the efficiency of the upload.

Of course, it is not recommended to use the Springmvc upload method, because this is the first time to upload the file to the server, only to do the verification!

We recommend using the front desk jquery and other ways to upload files, only need to do in the browser to verify, do not need to submit the server, more efficient transmission.

SPRINGMVC Series (iv) annotated way to upload files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.