Issue
I am following a file upload tutorial in Servlet
My system configuration is
- Eclipse
- Apache Tomcat 8.5
- Jdk:1.8
My index.html(form code):
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="UploadFileServlet" method="post">
Select a file to upload
<input type="file" value="file" name="source"/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
UploadFileServlet.java:
package com.upload;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadFileServlet
*/
@WebServlet("/UploadFileServlet")
public class UploadFileServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
ServletFileUpload sf=new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> multFileItems=sf.parseRequest(request);
System.out.println(multFileItems.isEmpty());
for(FileItem item:multFileItems)
{
item.write(new File("E:\\aman\\"+item.getName()));
}
}
catch(Exception e)
{
System.out.println(e);
}
}//End of doPost method
}
I do not understand why It does not work. It does not produce any exception.
Expected output:
I expected this code to upload the file which I had selected in my form in e:\aman\
folder, but it does not upload any file
You can reproduce this error by
https://drive.google.com/open?id=1oHnkV5Tmrp2jX8SU6Ilw_EYPWXQbsvv9
Solution
I changed the index.html
I added
enctype="multipart/form-data" to my form
<form action="UploadFileServlet" method="post" enctype="multipart/form-data">
Answered By - Aman
Answer Checked By - Cary Denson (JavaFixing Admin)