Note:
Before reading this question and its answer, please check your input element has name attribute.
I am trying to upload file using servlet. Eclipse console shows no errors. But the file is not getting uploaded. For me, it seems everything is fine. But I am making mistake somewhere.
In console I get just
Inside Servlet //Printed by code
Items: [] // Printed by Cdoe
Html Code:
<form action="ImageUploadServlet" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><label>Select Image: </label></td>
<td><input type="file" id="sourceImage" /></td>
<tr>
<td colspan="3">
<input type="submit" value="Upload"/><span id="result"></span>
</td>
</tr>
</table>
</form>
Servlet Code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
System.out.println("Inside Servlet");
if(!isMultiPart){
System.out.println("Form type is not multipart/form-data");
System.out.println("File Not Uploaded");
}
else
{
FileItemFactory dfit = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(dfit);
List aList = null;
try {
aList = sfu.parseRequest(request);
System.out.println("Items: "+aList);
}
catch (FileUploadException fue)
{
fue.printStackTrace();
}
Iterator itr = aList.iterator();
while(itr.hasNext())
{
FileItem fi = (FileItem) itr.next();
if(fi.isFormField())
{
System.out.println("File Name: "+fi.getFieldName());
System.out.println("File Size: "+fi.getSize());
try
{
File f = new File("D:/MyUploads/", fi.getName());
fi.write(f);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
System.out.println("It's Not Form Item;");
}
}
}
}
}
Any suggestions would be appreciated.
Thanks!
There are two problems:
First, you need to give the field a
name. It becomes then the request parameter name.Second, you need to handle the file uploads in the
elsecase ofFileItem#isFormField()as per the commons fileupload guide. Your code is currently ignoring them and doing only a sysout.Note that you need to use
FilenameUtils#getName()to extract the file name, because MSIE browser incorrectly sends the full client side file path along the file name. See also Commons FileUpload FAQ.You also need to keep in mind that this approach will overwrite any previously uploaded file with the same name. You may want to add an autogenerated suffix to the filename.
See also: