简体   繁体   English

在jsp中上传文件后,为什么无法从请求中访问参数?

[英]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. 我正在使用jsp和servlet来做到这一点。

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. 当我提交表单并获得servlet响应时,仅返回第一件事。

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. 您应该使用提取上传文件相同的 API(例如Apache Commons FileUpload)提取请求参数。 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() ). 这通常无法与调用getParameter()互换使用,因为请求正文只能被解析一次(最终用户不会发送相同的请求两次,一个要由文件上传解析API解析,另一个要由getParameter()解析) 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 创建一个名为FileUploader的类,该类返回ServletFileUpload对象

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 解析请求后,我将其存储在一个称为MultipartFormData的对象中,该对象可用于获取请求参数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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