spring--Note upload file. @RequestParam (value = "File1", required = false); __java Annotation Method

Source: Internet
Author: User
Tags button type cos create directory

Spring supports staging file uploads in Web applications. This support is implemented by Plug and Play multipartresolver.

In Spring2.0, Spring offers two out-of-the-box multipartresolver

1.Commons FileUpload (http://jakarta.apache.org/commons/fileupload)

2. COS FileUpload (Http://www.servlets.com/cos)

However, after spring2.5, only the Commons FileUpload is supported.

So, how do you use Multipartresolver in spring2.5 MVC based on annotations?

The following is an example of how to use the Commonsmultipartresolver execution attachment upload.

First we build a Web project, the engineering structure as shown in the following illustration:

The configuration of SPRINGMVC is no longer detailed here, and readers can refer to previous articles.

Here we only need to add the following to the Spring-servlet.xml to notify the spring load file upload processor:

<!--definition File upload processor-->
<bean id= "Multipartresolver"
Class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultencoding= "UTF-8"/>

When this processor is configured, spring intercepts the user request to see if it is an attachment upload type, enctype= "Multipart/form-data", and if so, the request flow is processed. Converts it to a Defaultmultiparthttpservletrequest object that encapsulates the contents of the attachment, such as:

Get List of attachment names

Iterator iterator = Multipartrequest.getfilenames ();

while (Iterator.hasnext ()) {

Loop out each attachment multipartfile multifile = Multipartrequest.getfile ((String) Iterator.next ()); System.out.println (Multifile.getoriginalfilename ()); }

Take a look at an example:

There are two upload text boxes on the page, as follows:

<form action= "<%=request.getcontextpath ()%>/demo/upload.do" enctype= "Multipart/form-data" method= "POST" >

File1:<input type= "File" Name= "File1" id= "File1"/>

<br></br>

File2:<input type= "File" Name= "File2" id= "File2"/>

<br></br>

<button type= "Submit" >submit</button>

</form>

Note that the Enctype property of the form must be set to Multipart/form-data, otherwise the attachment upload cannot be implemented.

When you select the file to upload, click the Submit button, the Controller processing method is as follows:

@RequestMapping (value = "/demo/upload.do")
 public String handleimport (
   @ Requestparam (value = "File1", required = False) Multipartfile file1,
    @RequestParam (value = "File2" , required = false) Multipartfile file2,
   model Model) throws IOException {
  List< filemodel> list = new arraylist<filemodel> ();
  if (file1!= null&&stringutils.hastext (File1.getoriginalfilename ())) {
    system.out.println (File1.getoriginalfilename ());

Filemodel FileModel1 = new Filemodel ();
Filemodel1.setname (File1.getoriginalfilename ());
Filemodel1.setsize (File1.getsize ());
String path = Service.savefiletoserver (File1, Asve_path);
Filemodel1.setpath (path);
List.add (FILEMODEL1);
}
if (file2!= null&&stringutils.hastext (File2.getoriginalfilename ())) {
System.out.println (File2.getoriginalfilename ());

Filemodel FileModel2 = new Filemodel ();
Filemodel2.setname (File2.getoriginalfilename ());
Filemodel2.setsize (File2.getsize ());
String path = Service.savefiletoserver (File1, Asve_path);
Filemodel2.setpath (path);
List.add (FILEMODEL2);

}
Model.addattribute ("list", list);
return "Demo/list";

}

Description

1. @RequestParam (value = "File1", required = false): Binds the file1 in the parameter to Multipartfile file1, At this point Commonsmultipartresolver has helped us to fill the attachment content into the multipartfile, where required = False is best set to False, unless you are sure that this parameter will be passed to controller, Otherwise, a parameter binding exception is thrown.

2.asve_path: A constant, file-saved path

3.service.savefiletoserver (): This method saves the uploaded file to the specified path.

4.getOriginalFilename (): File name

5.getSize (): File size

Here's The Savefiletoserver (), which saves the attachment to the specified path and returns the saved file full path:

Public String Savefiletoserver (multipartfile multifile, String path)
   throws IOException {
  //Create directory
  file dir = new File (path);
  if (!dir.exists ()) {
  & Nbsp;dir.mkdir ();
  }
  //reads the file stream and remains on the specified path
  inputstream inputstream = Multifile.getinputstream ();
   outputstream outputstream = new FileOutputStream (Path
    + Multifile.getoriginalfilename ());
  byte[] buffer = multifile.getbytes ();
  int bytesum = 0;
  int byteread = 0;
  while (byteread = inputstream.read (buffer)!=-1) {
   bytesum + = Byteread;
&nb Sp;  outputstream.write (buffer, 0, byteread);
   outputstream.flush ();
  }
  outputstream.close ();
  inputstream.close ();

return path + multifile.getoriginalfilename ();
}

OK, how about, Spring processing attachment upload is very simple.

In this case, if I do not know how many attachments I want to upload, and not to the corresponding parameter names, such as the use of fancyupload such as multiple attachment upload components, this How to deal with it.

In fact very simple, only need to add defaultmultiparthttpservletrequest multipartrequest parameter in the processor method, also take the above page example, the controller processing method is as follows:

@RequestMapping (value = "/demo/uploadmulti.do")
Public String Handleimport (model model,
Defaultmultiparthttpservletrequest multipartrequest) throws IOException {

list<filemodel> list = new arraylist<filemodel> ();
if (multipartrequest!= null) {
Iterator iterator = Multipartrequest.getfilenames ();

while (Iterator.hasnext ()) {
Multipartfile multifile =
Multipartrequest.getfile ((String) Iterator.next ());

if (Stringutils.hastext (Multifile.getoriginalfilename ())) {
System.out.println (Multifile.getoriginalfilename ());
Filemodel Filemodel = new Filemodel ();
Filemodel.setname (Multifile.getoriginalfilename ());
Filemodel.setsize (Multifile.getsize ());
String path = Service.savefiletoserver (multifile, Asve_path);
Filemodel.setpath (path);
List.add (Filemodel);
}

}
}

Model.addattribute ("list", list);
return "Demo/list";

}

Compared with the previous method, we no longer use multipartfile parameters, and instead of using defaultmultiparthttpservletrequest parameters, in fact, this is more convenient, can be batch processing.

In addition, we are configuring

Commonsmultipartresolver can control the size of each upload file, as follows:

<bean id= "Multipartresolver"

class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >

<!--one of the properties available; The maximum file size in bytes-->

<property name= "Maxuploadsize" value= "100000"/>

</bean>

PS: If you do not want to add configuration to the configuration file and want to use spring's support for multiple attachment uploads, how do you do this, refer to the following example:

@RequestMapping (value = "/test/upload2.do", method = POST)

Public String HandleImport2 (model model, HttpServletRequest request) {

Commonsmultipartresolver commonsmultipartresolver = new commonsmultipartresolver (

Request.getsession (). Getservletcontext ());

Set encoding

Commonsmultipartresolver.setdefaultencoding ("Utf-8");

if (Commonsmultipartresolver.ismultipart (Request)) {

Convert to multi-part Request

Multiparthttpservletrequest multipartrequest = Commonsmultipartresolver.resolvemultipart (request);

Iterator iterator = Multipartrequest.getfilenames ();

while (Iterator.hasnext ()) {

Multipartfile multifile = Multipartrequest.getfile ((String) Iterator.next ());

System.out.println (Multifile.getoriginalfilename ());

}

Commonsmultipartresolver.cleanupmultipart (multipartrequest);

}

return null;

}

Description: In this way you cannot declare multipartresolver in the spring configuration file, or you will not get the uploaded file content

OK, about spring annotation based attachment upload here, the relevant code can refer to the attachment.

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.