This is a simple example of how to upload files using JSP and Servlet 3.0 which is a part of Java EE 6. While in earlier versions of Servlets we had to use commons fileupload or other libraries, this feature has been integrated into the Servlet 3.0 specification. Here is the code for a simple servlet and a JSP file that makes a file upload request to the servlet.
Full post
- FileUploadServlet.java
package com.blogspot.aoj.servlet3;
Note:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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;
import org.apache.log4j.Logger;
@WebServlet(urlPatterns = "/fileUpload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static Logger logger = Logger.getLogger(FileUploadServlet.class);
public FileUploadServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
for (Part part : request.getParts()) {
logger.info(part.getName());
InputStream is = request.getPart(part.getName()).getInputStream();
int i = is.available();
byte[] b = new byte[i];
is.read(b);
logger.info("Length : " + b.length);
String fileName = getFileName(part);
logger.info("File name : " + fileName);
FileOutputStream os = new FileOutputStream("c:/temp/logs/" + fileName);
os.write(b);
is.close();
}
}
private String getFileName(Part part) {
String partHeader = part.getHeader("content-disposition");
logger.info("Part Header = " + partHeader);
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
return cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
}
}
return null;
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}- There is no need to use a deployment descriptor the @WebServlet annotation is enough, which uses the urlPatterns property to define servlet mappings
- The @MultipartConfig is used to indicate that the servlet expects requests wof multipart/form-data MIME type which is required for file upload. Using @MultipartConfig allows you to use the request.getParts get the parts of the request
- The getFileName method gets the file name from the content-disposition header.
- upload.jsp
<html>
<head>
<title>File Upload with Servlet 3.0</title>
</head>
<body>
<form action="fileUpload" enctype="multipart/form-data" method="post">
<input type="file" name="uploadFile" /> <input type="submit" /></form>
</body>
</html>