views:

215

answers:

2

Sorry but I'm totally new to jsp.

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

A: 

It's a bit complicated when using pure jsp/servlets, that's why Apache created commons-fileupload.

In short:

  1. define <input type="file" />
  2. set <form method="post" enctype="multipart/form-data">
  3. 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)

Bozho
I've no idea at all how to write the file...
http://www.roseindia.net/java/beginners/java-write-to-file.shtmljust, instead of `write`ing "hello", write item.get()
Bozho
Roseindia sucks. Point to the Sun Java IO tutorial: http://java.sun.com/docs/books/tutorial/essential/io/
BalusC
yeah.. it was the first link that got in my hands. :)
Bozho
+2  A: 
  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 {
        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);
        }
    }
    
  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.

BalusC
Applause for the detailed answer, but there is a downside to these step-by-step answers to beginner questions - the asker won't have moved his finger in order to achieve what he wanted, and that's not a good lesson. It's not always "stackoverflow guys are omniscient" ;)
Bozho