This section contains detailed description of @MultipartConfig annotation and its implementation with sample code.
The annotation @MultipartConfig is used to handle multipart/form-data requests of Servlet.
Using this annotation(@MultipartConfig) you can set the temporary storage directory, maximum size limit of total parts, threshold size after which it starts storing it permanently.
@MultipartConfig has following attributes :
Attribute |
Description |
| location | This attribute is used to set the location where files will be stored. You can also use it as temporary storage. |
| maxFileSize | Used for setting maximum size for file uploading. Default is -1L means unlimited. |
| maxRequestSize | This attribute describe the multipart/form-data requests' maximum size. |
| fileSizeThreshold | This attribute describe the threshold(size limit) after which the file will be stored/ written on disk. |
The tools and technology used in the example is given below :
In the below example, we are going to store / upload the file on disk using Servlet having @MultipartConfig annotation which makes Servlet capable of handling multipart/form-data requests :
UploadFile.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>File Upload</title> </head> <body> <h3>@MultipartConfig Annotation Example</h3> <FORM action="FileUpload" enctype="multipart/form-data" method="POST"> File Name: <INPUT type="text" name="filename"><br/> Upload File: <INPUT type="file" name="content"><br/> <INPUT type="submit" value="Submit"> </FORM> </body> </html>
FileUpload.java
package roseindia;
import java.io.IOException;
import java.io.PrintWriter;
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;
@WebServlet(name = "FileUpload", urlPatterns = { "/FileUpload" })
@MultipartConfig(location = "C:\\tmp", fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
public class FileUpload extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String filename=req.getParameter("filename");
// File will be moved from location to target directory
req.getPart("content").write("C:/data/"+filename+".txt");
if(req.getPart("content")!=null){
PrintWriter out = resp.getWriter();
out.write("<h3>File uploaded successfully</h3>");
}
}
}
When you run the HTML page, you will get the following form for uploading file :

When you upload the file, you will get the following page :
In data folder, you will get the following file (which you gave name email) :

|
Recommend the tutorial |
Ask Questions? Discuss: @MultipartConfig
Post your Comment