Skip to content

Instantly share code, notes, and snippets.

@0xffan
Created March 30, 2015 06:26
Show Gist options
  • Save 0xffan/06959764294dbef420a6 to your computer and use it in GitHub Desktop.
Save 0xffan/06959764294dbef420a6 to your computer and use it in GitHub Desktop.
File uploading with apache-commons-fileupload
import java.io.InputStream;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FilenameUtils;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
// ... (do your job here)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment