2

I'm using jsp and a servlet to do this.

I have a contact form that send a email with some data (name, subject, question,contact email etc) and a file.

when I submit the form, and get the servlet response only the first thing is returned.

String file= fileUpload(request); //upload the client's file and return the absolute      path of the file in the server
//testing the rest of parameters
 out.println("REQUEST LIST"
              "\n"   request.getParameter("name")
              "\n"   request.getParameter("mail")
              "\n"   request.getParameter("subject")
              "\n"   request.getParameter("ask")
              "\n");

In this order the file is uploaded succesfully, but the other parameters (name, mail etc) are null.


In the order below, the parameters are ok, they return the data correctly. But the file is not uploaded.

//testing the rest of parameters
out.println("REQUEST LIST"
              "\n"   request.getParameter("name")
              "\n"   request.getParameter("mail")
              "\n"   request.getParameter("subject")
              "\n"   request.getParameter("ask")
              "\n");
String file= fileUpload(request); //upload the client's file and return the absolute      path of the file in the server

How can I have both? Thanks!

2 Answers2

5

You should extract the request parameters using the same API (e.g. Apache Commons FileUpload) as you've extracted the uploaded file. This is usually not interchangeable with calling getParameter() as the request body can be parsed only once (the enduser ain't going to send the same request twice, one to be parsed by the file upload parsing API and other to be parsed by getParameter()).

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

Look if the following code helps you. This is just an example. You may have to tweak it

Create a class called FileUploader which returns ServletFileUpload object

public class FileUploader 
{
private static ServletFileUpload uploader;

private FileUploader()
{

}

public static synchronized ServletFileUpload getservletFileUploader(String tempDir, int maxSizeInMB) 
{
    if(uploader == null)
    {
        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(1024 * 1024);
        factory.setRepository(new File(tempDir));

        uploader = new ServletFileUpload(factory);

        uploader.setFileSizeMax(maxSizeInMB * 1024 * 1024);
    }

    return uploader;
}
}

Now you can process a request and read all the data

    protected MultiPartFormData handleMultiPartRequest(HttpServletRequest request)
throws FileSizeLimitExceededException
{
    if(!isMultipartRequest(request))
        return null;

    ServletFileUpload upload = FileUploader.getservletFileUploader(tempDir, 50);
    MultiPartFormData data = new MultiPartFormData();
    try
    {
        List<FileItem> items = upload.parseRequest(request);

        for (FileItem item : items) 
        {
            if(item.isFormField())
            {
                data.getParameters().put(item.getFieldName(), item.getString());
            }
            else
            {
                String filename = item.getName();

                //Internet explorer and firefox will send the file name differently
                //Internet explorer will send the entire path to the file name including 
                //the backslash characters etc ... we should strip it down
                //THIS IS HACKY
                if(filename.indexOf("\\") != -1)
                {
                    int index = filename.lastIndexOf("\\");
                    filename = filename.substring(index + 1);
                }


                if(filename == null || filename.equals(""))
                {
                    //do nothing 
                }
                else
                {
                    File uploadFile = new File(uploadDir + File.separator + randomFileName);
                    item.write(uploadFile);

                                            data.addFile(item.getFieldname(), item.getString());
                }
            }
        }
    }
    catch(FileSizeLimitExceededException e)
    {
        throw e;
    }
    catch(Exception e)
    {
        e.printStackTrace();

    }


    return data;
}

After parsing the request I am storing it in some object called MultipartFormData which can be used to get request parameters

public class MultiPartFormData {

private Hashtable<String, String> parameters;
    private Hashtable<String, String> uploadedFiles;

public MultiPartFormData()
{
    this.parameters = new Hashtable<String, String>();
    this.uploadedFiles = new Hashtable<String, String>();
}

public Hashtable<String, String> getParameters() {
    return parameters;
}
public void setParameters(Hashtable<String, String> parameters) {
    this.parameters = parameters;
}
    public void getParameter(String paramName) {
          if(this.parameters.contains(paramName))
                 return tyhis.parameters.get(paramName);
          return null;
    }
    public void addFile(String key, String filename) {
        uploadedFile.put(key, filename);
    }
    public void getFilename(String key) {
        uploadedFile.get(key);
    }
}
Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
jsshah
  • 1,741
  • 1
  • 10
  • 18
  • As to extracting the filename, just use `FilenameUtils#getName()`, exactly as demonstrated in the documentation of Apache Commons FileUpload (and in the code example behind the "see also" link in my answer). – BalusC Jul 26 '12 at 17:19
  • thanks for your answer, I can upload de the file, but i can't get de parameter from MultiPartFormData data. how do you do that? to upload the file I'm using this code MultiPartFormData data = handleMultiPartRequest(request); – Ignacio Arriagada Calquin Jul 27 '12 at 15:20
  • use String parameter = data.getParameter(paramName); It just looks up the hash table that we populated when we handled the multipart data – jsshah Jul 27 '12 at 17:55
  • it's not working, I solved this by saving the parameters as session parameters. `if (item.isFormField()) { session.setAttribute(item.getFieldName(), item.getString());` thanks for your answer! – Ignacio Arriagada Calquin Jul 27 '12 at 18:56
  • do not store this in session ... I have updated the code a bit more ... you can just have another map which maps the filename with the parameter name and then you can query multipartformdata – jsshah Jul 27 '12 at 19:09