Uploading Files with JSP
By Nisansa PereraI was fed up with some of the resources available on the net to do this.
This is how I got this done.
1. Enable your html to upload files
2. Use commons file upload
Then follow Apache commons file upload article to handle the file within your jsp. This is the code snippet to do that, extracted from commons file upload user guide.
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(yourMaxMemorySize);
factory.setRepository(yourTempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(yourMaxRequestSize);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
// Process the uploaded itemsReferences
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
// Process a file upload
if (writeToFile) {
File uploadedFile = new File(...);
item.write(uploadedFile);
} else {
InputStream uploadedStream = item.getInputStream();
...
uploadedStream.close();
}
}
}
For more information on commons file upload, use the their user guide.
- http://www.cs.tut.fi/~jkorpela/forms/file.html
- http://commons.apache.org/fileupload/using.html
No comments:
Post a Comment