通过单个连接将多个文件发送到servlet [英] Sending multiple files to a servlet with a single connection

查看:57
本文介绍了通过单个连接将多个文件发送到servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Java桌面客户端,该客户端将使用发布请求通过电线将多个文件发送到servlet.在servlet中,我从请求中获取输入流以接收文件.Servlet会将文件从流中读取时一一写入到磁盘.

该实现有几个要求:

  • 服务器只能使用一个HTTP请求(因此只有一个流)
  • 无论文件大小如何,该servlet都必须使用合理的固定内存量.

我曾考虑过将标记插入流中,因此我知道一个文件何时结束而下一个文件开始.然后,我将编写一些代码来解析servlet中的流,并根据需要开始编写下一个文件.

这就是事情……肯定有一个图书馆可以做到这一点.我浏览了Apache Commons,却一无所获.Commons File Upload很有趣,但是由于上传来自Java应用程序而不是浏览器,因此它只能解决接收端,而不是发送端.

关于库的任何想法,即使对于非常大的文件,也可以轻松地在单个流中进行多个文件传输,并且具有固定的内存预期?

谢谢.

解决方案

只需在POST请求正文上使用HTTP multipart/form-data 编码.在 RFC-2388 中进行了描述,并介绍了通过HTTP上传(多个)文件的标准方法.

您可以使用 Apache Commons HttpClient .

然后,您可以在Servlet端使用 Apache Commons Fileupload 处理上传的文件,常用的HTTP方式(或当您已经使用Servlet 3.0时,此答案(例如).

I'm writing a Java desktop client which will send multiple files over the wire to a servlet using a post request. In the servlet I'm getting the input stream from the request to receive the files. The servlet will write the files to disk, one by one as they're read from the stream.

The implementation has a couple of requirements:

  • Only one HTTP request must be used to the server (so only a single stream)
  • The servlet must use a reasonable fixed amount of memory, no matter what the size of the files.

I had considered inserting markers into the stream so I know when one file ends and the next one begins. I'd then write some code to parse the stream in the servlet, and start writing the next file as appropriate.

Here's the thing... surely there's a library to do that. I've looked through apache commons and found nothing. Commons File Upload is interesting but since the upload comes from a Java app, not a browser it only solves the receiving end, not the sending.

Any ideas for a library which easily allows multiple file transfers across a single stream with fixed memory expectations even for very large files?

Thanks.

解决方案

Just use HTTP multipart/form-data encoding on the POST request body. It's described in RFC-2388 and a standard way of uploading (multiple) files by HTTP.

You can do it with just java.net.URLConnection as described in this mini-tutorial, although it would generate lot of boilerplate code. A more convenienced approach would be using Apache Commons HttpClient.

In the servlet side you can then just use Apache Commons Fileupload to process the uploaded files the usual HTTP way (or when you're already on Servlet 3.0, the HttpServletRequest#getParts(), see also this answer for examples).

这篇关于通过单个连接将多个文件发送到servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆