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

时间:2012-07-26 16:48:41

标签: java jsp servlets email-attachments

我正在使用jsp和servlet来执行此操作。

我有一个联系表单,可以发送包含一些数据(姓名,主题,问题,联系电子邮件等)和文件的电子邮件。

当我提交表单时,只得到第一件事就是获取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");

按此顺序成功上传文件,但其他参数(名称,邮件等)为空。


按照以下顺序,参数正常,它们正确返回数据。但是文件没有上传。

//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

我怎么能同时拥有这两个? 谢谢!

2 个答案:

答案 0 :(得分:5)

您应该在解压缩上传文件时使用相同 API(例如Apache Commons FileUpload)提取请求参数。这通常不能与调用getParameter()互换,因为请求体只能被解析一次(最终用户不会发送两次相同的请求,一个要由文件上传解析API解析,另一个要解析) getParameter())。

另见:

答案 1 :(得分:2)

查看以下代码是否对您有所帮助。这只是一个例子。你可能需要调整它

创建一个名为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;
}
}

现在您可以处理请求并阅读所有数据

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

解析请求后,我将其存储在一个名为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);
    }
}