views:

1275

answers:

1

This just won't work. The problem is that I do not know enough to even know what is supposed to happen. I can't debug this code. I'd like to store upload to temporary folder "temp" and then to move them to "applets". Please help? The servlet is obviously being accessed, but I can't find the uploaded files... Thanks in advance.

Form (which is created using a scriptlet - I put this here if that could cause problems):

<%
out.write("<p>Upload a new game:</p>");
                    out.write("<form name=\"uploadForm\" action=\"game.jsp\" "
                    + "method=\"POST\" enctype=\"multipart/form-data\">"
                    + "<input type=\"file\" name=\"uploadSelect\" value=\"\" width=\"20\" />"
                    + "<br><input type=\"submit\" value=\"Submit\" name=\"uploadSubmitButton\" "
                    + "onclick = \"submitToServlet2('UploadGameServlet');\">"        
                    + "</form>");
 %>

Which calls this javascript:

function submitToServlet2(newAction)
    {
       document.uploadForm.action = newAction;
    }

Which in turn goes to the servlet (code included in full, since there may be some important element hiding)

package org.project;

import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
// import servlet stuff
import org.apache.commons.fileupload.*;


public class UploadGameServlet extends HttpServlet {

/** 
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    if (ServletFileUpload.isMultipartContent(request))
    {
        try 
        {
            // 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 items = upload.parseRequest(request); /* FileItem */

            File repositoryPath = new File("\\temp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);

            Iterator iter = items.iterator();
            while (iter.hasNext()) 
            {
                FileItem item = (FileItem) iter.next();
                File uploadedFile = new File("\\applets");
                item.write(uploadedFile);
            }            
        }
        catch (FileUploadException ex) 
        {
            Logger.getLogger(UploadGameServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (Exception ex) 
        {
            Logger.getLogger(UploadGameServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    PrintWriter out = response.getWriter();
    try {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet UploadGameServlet</title>");  
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet UploadGameServlet at " + request.getContextPath () + "</h1>");
        out.println("</body>");
        out.println("</html>");
    } finally { 
        out.close();
    }
}

}

+2  A: 
File repositoryPath = new File("\\temp");
File uploadedFile = new File("\\applets");

By trying to access these files without any sort of leading or absolute path, you are trying to write to files (not directories) named temp and applets under the current working directory. In an app server, the current working directory is usually the bin folder (depends on what app server you use, etc).

Some suggestions:

  1. Use an absolute path (preferably stored in web.xml or a properties file) to refer to the directory you want to save files to.
  2. You have to specify the name of the file you want to write to, you probably want to create some sort of random/unique name per request.
  3. Save yourself some keystrokes and use a member variable instead of all the Logger.getLogger(UploadGameServlet.class.getName()) references!
  4. Add some debugging, especially to see where you are writing your data to - log the result of repositoryPath.getAbsolutePath(), for example.
matt b
That was really helpful, thanks! It now saves the file... but it gets the value of the submit button instead of the file select input. Do you maybe know why?
pypmannetjies
In your original code, it looks like you were writing each item in the List items to the same file - possibly overwriting the file each time (I'm not sure how FileItem.write() works). You probably want to write to the file only under certain conditions, by checking FileItem.getFieldName()
matt b
Oh my! It works! It finally works! Thank you so very very much! You have possibly just saved my semester mark :)
pypmannetjies