首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么servlet在多部分请求中找不到FileItem?

为什么servlet在多部分请求中找不到FileItem?
EN

Stack Overflow用户
提问于 2012-01-06 09:50:05
回答 2查看 9.4K关注 0票数 1

我已经编写了一个Servlet,它使用Apache commons文件上传库处理文件上传。以下是部分代码:

代码语言:javascript
复制
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        try {
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

            // Set size threshold for storing upload
            fileItemFactory.setSizeThreshold(1 * 1024 * 50); // 50 KB

            // Set temporary directory to store uploaded files above threshold size
            fileItemFactory.setRepository(new File(TEMP_DIRECTORY));

            ServletFileUpload upload = new ServletFileUpload(fileItemFactory);

            //HashMap<String, String> params = new HashMap<String, String>();


            FileItemIterator iterator = upload.getItemIterator(request);
            upload.setSizeMax(REQUEST_MAX_SIZE);

            List items = upload.parseRequest(request);
            Iterator it = items.iterator();

            while (it.hasNext()) {
                FileItem item = (FileItem) it.next();

                if(item.isFormField()) {

                } else {
                    String contentType = item.getContentType();
                    String fileName = item.getName();
                    String fieldName = item.getFieldName();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    File uploadedFile = new File(PATH + "new_audio1.amr");

                    item.write(uploadedFile);

                    System.out.println("Field: " + fieldName);
                    System.out.println("File name: " + fileName);
                    System.out.println("Size: " + sizeInBytes);
                    System.out.println("Is in memory:" + isInMemory);
                }
            }

        } catch (Exception ex) {
            throw new ServletException(ex);
        }
    } else {
        throw new ServletException();
    }

出于某种原因,我不知道“项目”列表是空的,所以我无法抓取上传的文件。

对于上传本身,我已经编写了一些java代码:

代码语言:javascript
复制
File audioFile = new File("C:\\Users\\Soto\\Desktop\\test recording.amr");

    String url = "http://localhost:8080/AudioFileUpload/UploadServlet";
    String charset = "UTF-8";

    // random values
    String latitude = "145";
    String longitude = "132";
    String speed = "0";


    String query;
    try {
        query = String.format("latitude=%s&longitude=%s&speed=%s", URLEncoder.encode(latitude, charset), URLEncoder.encode(longitude, charset), URLEncoder.encode(speed, charset));
    } catch (UnsupportedEncodingException e) {
        query = String.format("latitude=%s&longitude=%s&speed=%s", latitude, longitude, speed);
    }

    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httpPost = new HttpPost(url + "?" + query);

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(audioFile, "audio/AMR");
    mpEntity.addPart("audioFile", cbFile);

    httpPost.setEntity(mpEntity);

    HttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        System.out.println(response.getStatusLine());

        if(responseEntity != null) 
            System.out.println(EntityUtils.toString(responseEntity));

        if(responseEntity != null) {
            EntityUtils.consume(responseEntity);
        }

        httpClient.getConnectionManager().shutdown();

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

我感觉这个文件已经被正确地附加和上传了。我也尝试过通过HTML使用multipart/form-data post请求来执行此操作,但仍然没有找到该文件。

我做错了什么?

编辑:我删除了doPost()开头的行和if语句:

代码语言:javascript
复制
ServletFileUpload.isMultipartContent(request);

然后上传就可以正常工作了。这个方法有没有可能消耗请求的“输入/输出/不管它是什么”流?

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-06 12:00:11

编辑:我删除了doPost()开头的行和if语句:

ServletFileUpload.isMultipartContent(request);

然后上传就可以正常工作了。这个方法有没有可能消耗请求的“输入/输出/不管它是什么”流?

这很奇怪。该方法所做的就是检查请求方法是否等于POST,以及Content-Type标头是否以multipart/开头。以下是最新Commons版本的源代码摘录(多年来没有太大变化):

代码语言:javascript
复制
public static final boolean isMultipartContent(
        HttpServletRequest request) {
    if (!"post".equals(request.getMethod().toLowerCase())) {
        return false;
    }
    String contentType = request.getContentType();
    if (contentType == null) {
        return false;
    }
    if (contentType.toLowerCase().startsWith(MULTIPART)) {
        return true;
    }
    return false;
}

你看,没什么令人震惊的。

也许您正在使用一个非常晦涩/有bug的servlet容器,它显示了一个错误,即当您调用request.getMethod()getContentType()时,请求正文将被隐式地使用。

票数 1
EN

Stack Overflow用户

发布于 2012-01-06 10:15:38

我想你忘了设置内容类型了?使用fiddler查看网络上发生了什么

为什么不使用MultiPartPostData?

http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/methods/MultipartPostMethod.html

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8752469

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档