How to retrieve uploaded image and save to a file

2019-01-23 22:19发布

This question already has an answer here:

Sorry but I'm totally new to jsp.

How to retrieve uploaded image and save to a file with jsp?

1条回答
We Are One
2楼-- · 2019-01-23 22:38
  1. Create a web project.
  2. 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>
    
  3. Go to Apache Commons FileUpload homepage, read both the User Guide and Frequently Asked Questions sections.

  4. Download the binaries of the following libraries:

  5. Unpack the zips and place the JAR files in the /WEB-INF/lib of your web project.

  6. Create a Servlet class with at least the following content:

    public class UploadServlet extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse 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);
        }
    }
    
  7. 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.

查看更多
登录 后发表回答