@MultipartConfig : Servlet 3.0 File Upload Example

@MultipartConfig : Servlet 3.0 File Upload Example

Up to now Servlet API did not provide any built in support for handling file upload. we used various open source libraries like Commons file upload and COS multipart parser. However supporting file upload is so common requirement for any web application that Servlet 3.0 Specification supports it out of the box. Web container itself can parse the multipart request and make mime attachments available through HttpServletRequest object.

A new annotation @MultiPartConfig has been introduced. When @MultiPartConfig is present on any servlet, it indicates that the servlet expects request of type multipart.

@MultipartConfig annotation

@MultipartConfig supports following attributes

  1. location - An absolute path to a directory on file system. It is important to remember that location doesnt support a path relative to application context. (I too don't know, why specification doesnt support context relative URLs). This location will be used to store files temporarily while processing parts, when the size of the file is bigger then fileSizeThreshold.
  2. fileSizeThreshold - The file size in bytes after which the file will be temporarily stored on disk.
  3. MaxFileSize - The maximum size allowed for uploaded files in bytes. If the size of any uploaded file is bigger then this. Container will throw an exception (tomcat throws IllegalStateException)
  4. maxRequestSize - The maximum size allowed for multipart/form-data request in bytes. Web container will throw and error If the over all size the all uploaded files goes beyond this.
@MultipartConfig example
@MultipartConfig(location="c:\\tmp", fileSizeThreshold=1024*1024, maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)

Two new methods have been introduced to HttpServletRequest interface.

public Collection<Part> getParts()
public Part getPart(String name)

request.getParts() returns collections of all parts. (if you have more then one input of type file). request.getPart(String name) returns a Part for given name. Here the name would be the name of the input field.

Javax.servlet.http.Part is an Interface, that provides access to information like, the headers, Content Type, and size of the file. Part interface provides a method write(String filename) to write the file with the given name. The file will be saved in the directory specified in the location attribute of @MultipartConfig annotation.

An Example of File Upload Servlet


FileUploadServlet
package com.servletworld;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/upload.html")
@MultipartConfig(location="c:\\tmp", fileSizeThreshold=1024*1024, maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)
public class FileUploadServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
getServletContext().getRequestDispatcher("/WEB-INF/pages/form.jsp").forward(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();

Collection<Part> parts = req.getParts();

out.write("<h2> Total parts : "+parts.size()+"</h2>");

for(Part part : parts) {
printPart(part, out);
part.write("samplefile");
}

}
private void printPart(Part part, PrintWriter pw) {
StringBuffer sb = new StringBuffer();
sb.append("<p>");
sb.append("Name : "+part.getName());
sb.append("<br>");
sb.append("Content Type : "+part.getContentType());
sb.append("<br>");
sb.append("Size : "+part.getSize());
sb.append("<br>");
for(String header : part.getHeaderNames()) {
sb.append(header + " : "+part.getHeader(header));
sb.append("<br>");
}
sb.append("</p>");
pw.write(sb.toString());

}
}

form.jsp
<html>
<head></head>
<body>
<p>Commons File Upload Example</p>
<form action="upload.html" enctype="multipart/form-data" method="POST">
<input type="file" name="file1"><br>
<input type="Submit" value="Upload File"><br>
</form>
</body>
</html>

How to run the example

Just create a directory with name fileupload inside the tomcat webapps directory. Compile the file upload servlet and put inside WEB-INF/classes directory under your fileupload application directory. Copy the form.jsp file under WEB-INF/pages directory of application. Start the server and you should be able to access the file upload servlet at URL http://localhost:8080/fileupload/upload.html


Note You will need Tomcat 7.x or any other Servlet 3.0 compliant container to run this example.


轉貼至 : http://www.servletworld.com/servlet-tutorials/servlet3/multipartconfig-file-upload-example.html

留言

這個網誌中的熱門文章

WPF - 深入 Style

C# – M$ Chart Control 自定 ToolTip 的顯示

Vue.js - 基礎介紹教學