I'm trying to implement images uploading using servlet and JSP.
My JSP page is pretty simple and has only the following form:
<form method="post" action="${pageContext.request.contextPath}/uploader" enctype="multipart/form-data">
<input type="file" name="file" value="Select an image..." />
<input type="submit" value="Upload Now" />
</form>
The corresponding servlet and servlet-mapping is described in web.xml
.
And my doPost
method looks as:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
FileItemFactory itemFactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(itemFactory);
if (!contentType.equals("image/png")) {
out.println("Only PNG image files supported.");
continue;
}
try {
List<FileItem> items = upload.parseRequest(request); // here is an error
for (FileItem item : items) {
String contentType = item.getContentType();
File uploadDir = new File(UPLOAD_DIR);
File file = File.createTempFile("img", ".png", uploadDir);
item.write(file);
out.println("File uploaded.");
}
} catch (FileUploadException e) {
out.println("Upload failed.");
return;
}
}
But the compiler complains on the following line: List<FileItem> items = upload.parseRequest(request);
:
The method
parseRequest(RequestContext)
in the file FileUploadBase is not applicable for the arguments (HttpServletRequest).
While in the answer How to upload files to server using JSP/Servlet? this method doesn't produce any errors:
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);