Sorry but I'm totally new to jsp.
How to retrieve uploaded image and save to a file with jsp?
Sorry but I'm totally new to jsp.
How to retrieve uploaded image and save to a file with jsp?
It's a bit complicated when using pure jsp/servlets, that's why Apache created commons-fileupload.
In short:
<input type="file" />
<form method="post" enctype="multipart/form-data">
In the servlet/jsp where you handle the form:
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
And then you proceed with java.io to write your file (I assume you know how to do this)
Create a JSP file with at least the following content:
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
Go to Apache Commons FileUpload homepage, read both the User Guide and Frequently Asked Questions sections.
Download the binaries of the following libraries:
Unpack the zips and place the JAR files in the /WEB-INF/lib
of your web project.
Create a Servlet class with at least the following content:
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResposne response) throws ServletException, IOException {
List<FileItem> items = null;
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form fields here the same way as request.getParameter().
// You can get parameter name by item.getFieldName();
// You can get parameter value by item.getString();
} else {
// Process uploaded fields here.
String filename = FilenameUtils.getName(item.getName()); // Get filename.
File file = new File("/path/to/uploads", filename); // Define destination file.
item.write(file); // Write to destination file.
}
}
// Show result page.
request.getRequestDispatcher("result.jsp").forward(request, response);
}
}
Map the servlet in web.xml as follows:
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>mypackage.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
That should be it. When you submit the form in the JSP, it will invoke the action /upload
which matches the <url-pattern>
of the servlet and then the servlet will do its task in the doPost()
method. At end it's all fairly simple. Hope this helps.