【问题标题】:multipart/form-data not working with servlets多部分/表单数据不适用于 servlet
【发布时间】:2012-01-12 00:45:26
【问题描述】:

我不确定为什么带有标签 enctype="multipart/form-data" 的 html 表单没有传递它应该传递的对象。 Mozilla 和 firefox 就是这种情况。

以IE为例,我使用html控件选择一个文件,它确实得到了它应该得到的。

现在我只想知道是否有任何替代方法可以用来通过 http 请求对象传递文件,因为 enctype="multipart/form-data" 似乎存在一些兼容性问题,但我不太确定

任何建议将不胜感激! :D

【问题讨论】:

标签: java html jsp upload


【解决方案1】:

知道了。如果其他人可能有这样的问题,这是我的问题。我为我检查了文件的内容类型,以确保传递的对象是某种类型。在 IE 中,它返回 application/x-zip-compressed THAT IS ON IE,但 mozilla 和 chrome 似乎为 zip 文件返回了不同的内容类型,即 application/octet-stream。

所以我刚刚将 application/octet-stream 添加到有效的文件类型中,它现在似乎可以工作了

【讨论】:

    【解决方案2】:

    首先,您必须提供一点代码来显示您所做的事情,并了解哪里出了问题。无论如何,我假设您必须使用 HTML 文件上传控件将文件上传到服务器。

    文件上传或者说multipart/form-data编码类型支持在HttpServlet实现中没有实现。所以,request.getParameter() 不适用于multipart/form-data。您必须使用为此提供支持的其他库。 Apache Commons File Upload 就是一个很好的例子。他们的using fileupload 指南将帮助您开始使用该库。这是一个简单的例子(使用文件上传指南编译)。

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    
    if (isMultipart) {
        // 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 /* FileItem */ items = upload.parseRequest(request);
    
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
    
            if (item.isFormField()) {
                // Process form field.
                String name = item.getFieldName();
                String value = item.getString();
            } else {
                // Process uploaded file.
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
    
                if (writeToFile) {
                    File uploadedFile = new File("path/filename.txt");
                    item.write(uploadedFile);
                }
            }
        }
    } else {
        // Normal request. request.getParameter will suffice.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-13
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2022-10-04
      • 1970-01-01
      相关资源
      最近更新 更多