How to Receive File Uploads (Multi-Part File Upload)
Unfortunately the Servlet API 2.5 does not support file upload yet (3.0 does). Handling file uploads from a form is rather complicated, so you should use a library to parse the upload. The most popular choice for this is Apache Commons FileUpload, as it is free, flexible and fairly easy to use.
The following example should give you an idea of how to use Apache Commons FileUpload. For details you should consult the documentation provided by the project.
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
import javax.servlet.http.*;
import java.nio.*;
import java.io.*;
import java.util.*;
// Show form to let user upload a text file. Then print content as ASCII.
public class UploadServlet extends HttpServlet {
private void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/html; charset=US-ASCII");
response.setCharacterEncoding("US-ASCII");
PrintWriter writer = response.getWriter();
writer.print("<html><head><title>Calculator</title></head><body>");
writer.print("<form method='POST' enctype='multipart/form-data'><br>");
writer.print("<input type='file' name='file'><input type='submit'>");
writer.print("</form></html>");
}
private void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
if (!ServletFileUpload.isMultipartContent(request)) {
throw new ServletException("file missing");
try {
response.setContentType("text/plain; charset=US-ASCII");
response.setCharacterEncoding("US-ASCII");
PrintWriter writer = response.getWriter();
writer.println("Processing upload:\n");
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
for (FileItem item: items) {
w.printf("File '%s' for field '%s':\n", item.getName(), item.getFieldName());
byte[] content = item.get(); // warning: use streams for long files
// this line decodes the byte array content as ASCII into a char array:
char[] decoded = Charset.forName("US-ASCII")
.decode(ByteBuffer.wrap(content)).array();
w.print(decoded);
w.print("\n\n");
}
}
catch (FileUploadException e) {
throw new ServletException(e);
}
}
}