【问题标题】:Android - Uploading a file to a java servlet and using Apache IOUtils to handle itAndroid - 将文件上传到 java servlet 并使用 Apache IOUtils 处理它
【发布时间】:2013-11-17 18:05:14
【问题描述】:

我正在使用以下教程在 Android 中上传文件:

http://reecon.wordpress.com/2010/04/25/uploading-files-to-http-server-using-post-android-sdk/

在服务器端,我使用带有 Apache IOUtils 的 Java servlet 来处理它。

ServletFileUpload fileUpload = new ServletFileUpload();
FileItemIterator fileItemIterator = fileUpload.getItemIterator(request);
while (fileItemIterator.hasNext()) {
  FileItemStream filestream = fileItemIterator.next();
  doStuff(filestream);
}

在浏览器中一切正常,但在 Android 上,我的问题是当我在文件流上调用 getContentType 时,它​​返回 null。 为什么这里有差异?我没有处理 getContentType 的 null 值,因为有些东西告诉我不能为 null。

【问题讨论】:

    标签: java android servlets file-upload


    【解决方案1】:

    我使用 Wireshark 查看浏览器实际发送的内容。 在 Content-Disposition 之后(例如,“Content-Type: application/pdf\r\n\r \n”。 因此,在文件上传教程中,在以下行之后:

    dos.writeBytes("Content-Disposition: form-data;name=\"uploadedfile\";" + "filename=\"" + fileName + "\"" + lineEnd);
    

    我刚刚添加了:

    String mimeType = URLConnection.guessContentTypeFromName(file.getName());
    dos.writeBytes("Content-Type: " + mimeType + lineEnd);
    

    现在它接缝上传过程工作正常。

    当然,对于很多扩展,mimeType 可能会为 null,所以应该根据需要进行检查。

    【讨论】:

      猜你喜欢
      • 2020-10-17
      • 2014-02-20
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      相关资源
      最近更新 更多