无法将图像文件从 Android 应用程序发布到 Tomcat 上托管的 Java servlet

发布于 2024-11-25 15:37:55 字数 1089 浏览 1 评论 0原文

我正在开发的 Android 应用程序的一个功能是拍照并通过 HTTP Post 将其上传到 Java servlet。我找到了许多关于一般过程应该如何工作的示例,并尝试了所有这些示例。目前,代码如下所示:

Client:

String fileName = pathToFile;
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(path);
MultipartEntity entity = new MultipartEntity();
FileBody fileBody = new FileBody(new File(fileName));
entity.addPart("file", fileBody);
method.setEntity(entity);

HttpResponse response = httpclient.execute(method);

Server:

List<FileItem> fileItems =
new ServletFileUpload( new DiskFileItemFactory( 1024 * 1024, new File("C:\\tmp" ))).
parseRequest(request);

for ( FileItem item : fileItems ) {
String fieldName = item.getFieldName();

if ( item.isFormField()) { 
    item.getString();
}
else {
    item.getInputStream();
} // File uploaded
}

现在,我不担心如何处理输入流,因为当我们调用 parseRequest(request) 并出现以下错误时,此代码会失败: org.apache.tomcat.util.http.fileupload.MultipartStream$MalformedStreamException:流意外结束

我是 Apache HttpUpload 库的新用户。我在这里缺少什么?

提前致谢。

One feature of an Android app I am working on is to take a picture and upload it via HTTP Post to a Java servlet. I have found a number of examples of how the general process should work, and tried all of them. Currently, the code looks like this:

Client:

String fileName = pathToFile;
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(path);
MultipartEntity entity = new MultipartEntity();
FileBody fileBody = new FileBody(new File(fileName));
entity.addPart("file", fileBody);
method.setEntity(entity);

HttpResponse response = httpclient.execute(method);

Server:

List<FileItem> fileItems =
new ServletFileUpload( new DiskFileItemFactory( 1024 * 1024, new File("C:\\tmp" ))).
parseRequest(request);

for ( FileItem item : fileItems ) {
String fieldName = item.getFieldName();

if ( item.isFormField()) { 
    item.getString();
}
else {
    item.getInputStream();
} // File uploaded
}

Right now, I am not worried about what to do with the input stream, because this code fails when we call parseRequest(request) with this error:
org.apache.tomcat.util.http.fileupload.MultipartStream$MalformedStreamException: Stream ended unexpectedly

I am a new user of the Apache HttpUpload library. What am I missing here?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

命硬 2024-12-02 15:37:55

尝试使用构造函数:

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

默认使用 STRICT 模式,这可能是问题所在。

Try using the constructor :

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

The default is using mode STRICT and this may be the problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文