Form form upload file using multipart request processing

Source: Internet
Author: User
Tags tojson

One of the more common features when developing Web applications is to allow users to upload local files to the server using multipart requests, which is one of the advantages of Grails's rugged cornerstone--spring MVC. Spring extends the HttpServletRequest interface of the servlet API so that it can handle file uploads well. The expanded interface is named Org.springframework.web.multipart.MultipartHttpServletRequest, and its contents are shown in Listing 7-31.

Listing 7-31 Org.springframework.web.multipart.MultipartHttpServletRequest Interface

Interface Multiparthttpservletrequest extends HttpServletRequest {

Public Multipartfile getFile (String name);

Public Map getfilemap ();

Public Iterator getfilenames ();

}

As the listing shows, the Multiparthttpservletrequest interface simply expands the default HttpServletRequest interface and provides some way to handle the request file.

7.10.1 using multipart requests

In fact, if a multipart request is found, it indicates that there is a request object in the controller instance that implements the multipart HttpServletRequest interface. We can use the method shown in listing 7-31 to access the upload file in the multipart request, but before processing the upload file, take a look at the contents of the upload form, as shown in Listing 7-32.

Listing 7-32 Sample Upload Form

<form action= "Upload" enctype= "Multipart/form-data" >

<input type= "File" name= "MyFile"/>

<input type= "Submit" value= "upload! "/>

</form>

The bold display is the part that needs attention, in fact an upload form only needs to meet the following two points.

The property value of the L Enctype property is set to Multipart/form-data.

The property value of the Type property of input is set to file.

In the previous example, the value of the attribute type in the,<input> tag is file, and the value of the Name property is MyFile, and the Name property value is required. is because the value of the Name property is required when using the GetFile method of the interface multiparthttpservletrequest. For example, in Listing 7-33, the upload operation in the code reads the upload file from the request.

Listing 7-33 reading the upload file

def upload = {

def file = Request.getfile (' MyFile ')

Process the file

}

Note The GetFile method does not return an instance of Java.io.File, but instead returns Org.springframework.web. Multipart. For an example of Multipartfile, refer to listing 7-34 for more information about Org.springframework.web.multipart.MultipartFile. If the file is not found in the request, the GetFile method returns NULL.

Listing 7-34 Org.springframework.web.multipart.MultipartFile Interface

Interface Multipartfile {

Public byte[] GetBytes ();

Public String getcontenttype ();

Public Java.io.InputStream getInputStream ();

Public String getName ();

Public String getoriginalfilename ();

Public long getsize ();

public boolean isEmpty ();

public void TransferTo (Java.io.File dest);

}

A number of useful methods are defined in the Multipartfile interface.

L Use the GetSize () method to get the file length to determine the size of the file that is allowed to be uploaded.

L Use the IsEmpty () method to determine whether the uploaded file is an empty file, to determine whether to reject the empty file.

L Use the getInputStream () method to read the file as a Java.io.InputStream stream object.

L Use the getContentType () method to obtain the file type, which determines which file types are allowed to be uploaded.

L Use the Transferto (dest) method to write the uploaded file to the file specified on the server.

For example, if the uploaded file is not empty and the size is not less than 1024 bytes, then it can be implemented in the code in Listing 7-35.

Listing 7-35 File Upload example

def upload = {

def file = Request.getfile (' MyFile ')

if (file &&!file.empty && file.size < 1024) {

File.transferto (New Java.io.File ("/local/server/path/${file.name}"))

}

}

Direct use of multiparthttpservletrequest instances can be used to manage file uploads, but the actual application often needs to read the file contents.

But if you have multiple files uploaded at the same time, you need to upload the

@RequestMapping ("/stadium/addpic.json")
@ResponseBody
public void Addpicstadium (HttpServletRequest request,
HttpServletResponse response) {
map<string, object> messages = new hashmap<string, object> ();
String Imgurl = "";
Create a general-purpose multi-part parser
Commonsmultipartresolver multipartresolver = new Commonsmultipartresolver (Request.getsession (). GetServletContext () );
Setting the Encoding method
Multipartresolver.setdefaultencoding ("Utf-8");
Determine if request has a file upload, that is, multipart requests
if (Multipartresolver.ismultipart (request)) {
try{
Convert to multi-part Request
Multiparthttpservletrequest multirequest = (multiparthttpservletrequest) request;
Multiparthttpservletrequest multirequest = Multipartresolver.resolvemultipart (request);
Get all the file names in request
list<multipartfile> files = multirequest.getfiles ("FileUpload");
int len = Files.size ();
Limit the number of images uploaded
if (Len > 6) {
Messages.put ("Success", false);
Messages.put ("msg", "Upload a picture failed, can only upload 6 photos and below the picture!");
ToJson (response, messages);
Return
}
Iterator<string> iter = Multirequest.getfilenames ();

int i=0;
map<string, string> map = new hashmap<string, string> ();
while (Iter.hasnext ()) {
Jsonarray ja = new Jsonarray ();
for (Multipartfile multiparfile:files) {

Record the time when the upload process started, to calculate the upload time
int pre = (int) system.currenttimemillis ();
Get upload file
Multipartfile file = Multirequest.getfile (Iter.next ());

Get the name of the uploaded file
String clientName = Multiparfile.getoriginalfilename ();
System.out.println (ClientName);
if (file! = null) {
Get the file name of the current upload file
String myfilename = File.getoriginalfilename ();
If the name is not "", it indicates that the file exists, otherwise the file does not exist
if (Myfilename.trim () = "") {
if (!clientname.equals ("")) {

String fileName = Multiparfile.getoriginalfilename ();
int lastnum = Filename.lastindexof (".");
String Houzhui = filename.substring (Lastnum, Filename.length ());
Rename the uploaded file name
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyymmddhhmmss");
String filenewname = Sdf.format (New Date ()) +system.currenttimemillis () +houzhui;

String fileupdatename = Filename.replace (FileName, filenewname);
System.out.println (Fileupdatename);

Define the upload path
String path = Request.getsession (). Getservletcontext (). Getrealpath ("Upload");
Imgurl + = "upload/" +fileupdatename+ ",";
File LocalFile = new file (path,fileupdatename);
Multiparfile.transferto (LocalFile);
System.out.println ("FileName:" +filename);
System.out.println ("Imgurl:" +imgurl);
Jsonobject Jo = new Jsonobject ();
try {
Jo.put ("FileName", fileupdatename);
Jo.put ("Imgurll", Imgurl);
} catch (Jsonexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

Ja.put (Jo);

Map.put (FileName, Imgurl);
}
}
//}
Messages.put ("Success", true);
Messages.put ("msg", "Upload picture Succeeded!");
Messages.put ("Imgmap", JA);
Messages.put ("Length", Len);
}catch (IllegalStateException e) {
E.printstacktrace ();
Messages.put ("Success", false);
Messages.put ("msg", "Upload picture Failed!");
}catch (IOException e) {
E.printstacktrace ();
Messages.put ("Success", false);
Messages.put ("msg", "Upload picture Failed!");
}
}
ToJson (response, messages);
}

Form form upload file using multipart request processing

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.