Apache Commons logo Commons FileUpload

Using FileUpload

Your application should detect whether or not FileUpload should be invoked, based on the HTTP method and the content type of the request.

Assuming that you have decided that FileUpload should be invoked, you might write the following code to handle a file upload request:

DiskFileItemFactory factory = new DiskFileItemFactory();
// Set upload parameters
factory.setSizeThreshold(MAX_MEMORY_SIZE);
factory.setRepository(new File(TEMP_DIR));

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload( factory );
upload.setSizeMax(MAX_UPLOAD_SIZE);

// Parse the request
List<FileItem> items = upload.parseRequest(request);

// Process the uploaded fields
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = iter.next();

    if (item.isFormField()) {
        processTextParameter(request, item);
    } else {
        processFileParameter(request, item);
    }
}