简体   繁体   中英

Why I can't get access to parameters from a request after upload a file in jsp?

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!

You should extract the request parameters using the same API (eg 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:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM