如何检索上传的图像并使用JSP保存到文件?

时间:2009-12-02 07:49:17

标签: image jsp file-upload

很抱歉,我对jsp完全不熟悉。

如何检索上传的图像并使用jsp保存到文件?

1 个答案:

答案 0 :(得分:9)

  1. 创建一个Web项目。
  2. 创建至少包含以下内容的JSP文件:

    <form action="upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit">
    </form>
    
  3. 转到Apache Commons FileUpload homepage阅读 User GuideFrequently Asked Questions部分。

  4. 下载以下库的二进制文件

  5. 解压缩拉链并将JAR文件放在网络项目的/WEB-INF/lib中。

  6. 创建一个至少包含以下内容的Servlet类:

    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. 将weblet映射到web.xml中,如下所示:

    <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>
    
  8. 那应该是它。当您在JSP中提交表单时,它将调用与servlet的/upload匹配的操作<url-pattern>,然后servlet将在doPost()方法中执行其任务。最后,这一切都相当简单。希望这会有所帮助。