Java servlet 3.0 File upload

Source: Internet
Author: User

In the past, processing file uploads is a painful thing, mostly with the help of open source upload components, such as Commons fileupload. Now, very convenient, convenient to the most convenient than those components. The previous HTML-side upload form doesn't have to change anything, it's the same. Multipart/form-dataMIME type. There are two things you need to do to have the servlet support uploading
    1. Need to add multipartconfig annotations
    2. Get the part file object from the Request object
However, in practice, there are some details, such as setting the maximum upload file size, upload the file save path. You need to be familiar with multipartconfig annotations, labeled above @webservlet, with the following properties:

Property name type is optional Description
Filesizethreshold Int Is When the amount of data is greater than this value, the content is written to the file.
Location String Is Store the generated file address.
MaxFileSize Long Is Maximum number of files allowed to upload. The default value is-1, which means there is no limit.
Maxrequestsize Long Is The maximum number of requests for the Multipart/form-data, the default value is-1, which means there is no limit.

Some practical suggestions:
    1. If you upload a file, you just need to set maxfilesize familiar.
    2. To upload multiple files, you may need to set the Maxrequestsize property to set the maximum amount of time to upload data.
    3. The upload process whether a single file over maxfilesize value, or upload the total amount of data greater than Maxrequestsize value will throw illegalstateexception exception;
    4. The Location property is both the save path (when writing, you can ignore the path setting) and the path to save temporary files during the upload process, and once the Part.write method is executed, the temporary files are automatically purged.
    5. However, the Servlet 3.0 specification also shows that it does not provide a way to get the upload file name, although we can get it indirectly through the Part.getheader ("Content-disposition") method.
    6. How to read Multipartconfig annotation property values, the API does not provide a direct read method, can only be obtained manually.
To an example, upload the foreground page: Background processing servlet:
/**
* Upload file test location for temporary file save path
*
*/
@MultipartConfig (location = "/tmp", MaxFileSize = 1024 * 1024 * 10)
@WebServlet ("/upload")
public class Uploadfileaction extends HttpServlet {
Private static final long serialversionuid = 92166165626L;
Private static final Log log = Logfactory.getlog (Uploadfileaction.class);
Get annotation Information
Private static final Multipartconfig config;

static {
Config = UploadFileAction.class.getAnnotation (multipartconfig.class);
}

protected void doget (HttpServletRequest request,
HttpServletResponse response) throws Servletexception, IOException {
Request.getrequestdispatcher ("/upload.jsp"). Forward (request, response);
}

protected void DoPost (HttpServletRequest request,
HttpServletResponse response) throws Servletexception, IOException {
To avoid garbled characters when getting file names
Request.setcharacterencoding ("UTF-8");

Part part = NULL;
try {
<input name= "File" size= "type=" "File"/>
Part = Request.getpart ("file");
} catch (IllegalStateException ise) {
Upload a file that exceeds the Maxrequestsize or MaxFileSize value noted in the annotation
if (config.maxrequestsize () = = -1l) {
Log.info ("The part in the request is larger than maxfilesize");
} else if (config.maxfilesize () = = -1l) {
Log.info ("The request body is larger than maxrequestsize");
} else {
Log.info ("The request body is larger than maxrequestsize, or any part of the request is larger than maxfilesize");
}

Forwarderrorpage (Request, Response, "Upload file too large, please check the input is wrong!") ");
Return
} catch (IOException Ieo) {
A problem occurred while receiving data
Log.error ("I/O error occurred during the retrieval of the requested part");
} catch (Exception e) {
Log.error (E.tostring ());
E.printstacktrace ();
}

if (part = = null) {
Forwarderrorpage (Request, Response, "The upload file is abnormal, please check the input is wrong!") ");
Return
}

Get the original name of the file, eg: Test document. pdf
String fileName = Uploadutils.getfilename (part);

Log.info ("ContentType:" + part.getcontenttype ());
Log.info ("FileName:" + filename);
Log.info ("fileSize:" + part.getsize ());
Log.info ("header names:");
For (String headerName:part.getHeaderNames ()) {
Log.info (Headername + ":" + Part.getheader (headername));
}

String savename = System.currenttimemillis () + "."
+ filenameutils.getextension (fileName);

Log.info ("Save the file with new name:" + savename);

Because a path is specified in the annotation, you can specify a file name to write to
A temporary file will be generated under the annotations specified location path before the Write method is executed
Part.write (Savename);

Request.setattribute ("filename", filename);
Request.getrequestdispatcher ("/uploadresult.jsp"). Forward (Request,
Response);
}

private void Forwarderrorpage (HttpServletRequest request,
HttpServletResponse response, String errmsg)
Throws Servletexception, IOException {
Request.setattribute ("ErrMsg", errmsg);

Request.getrequestdispatcher ("/upload.jsp"). Forward (request, response);
}
}
The function of getting the file name is simple:
/**
* How to get the uploaded file name, the API does not provide a direct method, can only be obtained from the Content-disposition property

* @param part
* @return
*/
protected static String GetFileName (part part) {
if (part = = NULL)
return null;

String fileName = Part.getheader ("content-disposition");
if (Stringutils.isblank (FileName)) {
return null;
}

Return Stringutils.substringbetween (FileName, "filename=\", "\" ");
}
After the file upload is successful, and the log output is as follows: You can see the part contains content-dispositionproperty, you can easily extract the file name from the value. Most of the uploaded files that are temporarily generated are suffixed with. tmp, roughly as follows: to make the upload error, you can see the approximate temporary file on the save path. Example of a background servlet that uploads multiple files at a time:
/**
* Multi-File Upload support
* @author Yongboy
* @date 2011-1-14
* @version 1.0
*/
@MultipartConfig (
Location = "/home/yongboy/tmp/",
MaxFileSize = 1024L * 1024L,//maximum value per file
Maxrequestsize = 1024L * 1024L * 10L//One-time upload maximum, if only one file can be uploaded at a time, the setting of maxrequestsize meaning is not big
)
@WebServlet ("/uploadfiles")
public class Uploadfilesaction extends HttpServlet {
Private static final long serialversionuid = 2304820820384L;
Private static final Log log = Logfactory.getlog (Uploadfilesaction.class);

protected void doget (HttpServletRequest request,
HttpServletResponse response) throws Servletexception, IOException {
Request.getrequestdispatcher ("/uploads.jsp"). Forward (request, response);
}

protected void DoPost (HttpServletRequest request,
HttpServletResponse response) throws Servletexception, IOException {
Request.setcharacterencoding ("UTF-8");

Collection parts = null;
try {
Parts = Request.getparts ();
} catch (IllegalStateException ise) {
A file may be larger than the specified file size maxfilesize, or the submission data is greater than maxrequestsize
Log.info ("Maybe the request body is larger than maxrequestsize, or any part of the request is larger than maxfilesize");
} catch (IOException IoE) {
A pull IO exception error was encountered while getting a file
Log.error ("An I/O error occurred during the retrieval of the part, the this request");
} catch (Exception e) {
Log.error ("The request body is larger than maxrequestsize, or any part of the request is larger than maxfilesize");
E.printstacktrace ();
}

if (parts = = NULL | | parts.isempty ()) {
Doerror (Request, Response, "The upload file is empty!") ");
Return
}

The front end has several file components, which correspond to several part objects
List fileNames = new ArrayList ();
For (part Part:parts) {
if (part = = null) {
Continue
}
This is saved directly from the source file name
String fileName = Uploadutils.getfilename (part);

if (Stringutils.isblank (FileName)) {
Continue
}

Part.write (FileName);
Filenames.add (FileName);
}

Request.setattribute ("FileNames", fileNames);
Request.getrequestdispatcher ("/uploadsresult.jsp"). Forward (Request,
Response);
}

private void Doerror (HttpServletRequest request,
HttpServletResponse response, String errmsg)
Throws Servletexception, IOException {
Request.setattribute ("ErrMsg", errmsg);

This.doget (request, response);
}
}
Bulk upload is simple, but there is a risk that any file exceeding the MaxFileSize value means that the entire upload will fail. If not unlimited size, then there is no such worries. In short, in Servlet 3.0, either uploading a file, or multiple bulk uploads is very simple, but to handle the exception, to avoid errors.

Java servlet 3.0 File upload

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.