1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
<%@ page import="org.apache.commons.fileupload.*, java.util.List, java.io.File, java.util.Iterator" %>
<%
boolean isMultipart = FileUpload.isMultipartContent(request);
/*if(!isMultipart){
request.setAttribute("msg", "Request was not multipart!");
request.getRequestDispatcher("msg.jsp").forward(request, response);
return;
}*/
DiskFileUpload upload = new DiskFileUpload();
// parse this request by the handler
// this gives us a list of items from the request
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
// check if the current item is a form field or an uploaded file
if(item.isFormField()) {
// get the name of the field
String fieldName = item.getFieldName();
// if it is name, we can set it in request to thank the user
if(fieldName.equals("name"))
request.setAttribute("msg", "Thank You: " + item.getString());
} else {
// the item must be an uploaded file save it to disk. Note that there
// seems to be a bug in item.getName() as it returns the full path on
// the client's machine for the uploaded file name, instead of the file
// name only. To overcome that, I have used a workaround using
// fullFile.getName().
File fullFile = new File(item.getName());
File savedFile = new File(getServletContext().getRealPath("//"),
fullFile.getName());
item.write(savedFile);
}
}
request.getRequestDispatcher("msg.jsp").forward(request, response);
%> |