The Multipart annotation, introduced by EE 6, is very helpful to create a multipart upload.
First you need to create an upload form with method „post“ and enctype „multipart“.
fileupload.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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>Fileuploads</title> </head> <body> <form action="/OCEJWCD/fileupload" method="POST" enctype="multipart/form-data"> <input type="file" name="name"> <input type="submit" value="POST"> </form> </body> </html>
Next you can easily annotate your request accecpting servlet class with @WebServlet and @MultipartConfig. The MultipartConfig tells the servlet that there will be an incoming multipart upload and you’ll be able to access these parts via the HttServletRequest object.
FileUpload.java
package de.joerndettmer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; 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(urlPatterns = "/fileupload", name = "fileuploadServlet") @MultipartConfig public class FileUpload extends HttpServlet { private static final long serialVersionUID = 2575996974446997345L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Collection<Part> filePart = req.getParts(); FileOutputStream fos = new FileOutputStream(new File("fileupload.txt")); for (Part part : filePart) { int read = 0; InputStream filecontent = part.getInputStream(); final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { fos.write(bytes, 0, read); } } fos.flush(); fos.close(); } }
For further information see: MultipartConfig Link