将 URL 指定的文档上传到字节数组
我有一个 html 表单,其中一个字段将采用指向(可能是二进制)文件(例如图像)的 url。 url可以指向服务器无法访问的本地资源,因此需要由客户端获取。 (这个获取是另一点,我的问题是关于编写 servlet。)
我想将此获取的结果上传到 Java servlet(通过 http POST 请求)并将其放入字节数组中。由于这是一个低级表示,我不确定是否应该使用 Apache 的 FileUpload。
另一点让我困惑的是,FileUpload 中的 FileItem 只提供了一个 OutputStream,而我本来希望使用一个 InputStream 来读取文件。
学习FileUpload后我陷入困境。我可能对网络应用程序开发的基础知识还不够。
我应该如何构建这个功能?请注意,我是 Java 开发这个领域的新手(尽管我的一般(即 SE)Java 技能非常好)。
I have an html-form with a field that will take a url pointing to a (possibly binary) file (e.g. an image). The url can point to a local resource that the server can't reach, so it needs to be fetched by the client. (This fetching is another point, my question is about writing the servlet.)
I want to upload the result of this fetch to a Java servlet (through a http POST request) and put it into an array of bytes. Since this is a low-level representation, I'm not sure if I should use Apache's FileUpload.
Another point that confused me, is that FileItem
s in FileUpload only provide an OutputStream
where I was expecting an InputStream
to read the file.
I'm stuck after studying FileUpload. I may be that my basic knowledge of web-app development falls short.
How should I build this functionality? Please note that I'm new to this corner of Java development (although my general (i.e. SE) Java skills are very good).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
继续使用 FileUpload,不要自己重新发明它。这会浪费时间。
我不知道为什么你认为
FileItem
只提供OutputStream
,还有一个getInputStream()
方法。只需将其写入ByteArrayOutputStream
。您只需要记住,如果有很多用户同时上传文件,这可能会增加服务器的内存使用量。字节数组的每个字节都会占用 JVM 内存的一个字节。因此,假设您有 100 个并发用户,每个用户上传一个 10MB 的文件,那么 1GB 的服务器内存就被浪费了。
Just keep using FileUpload, don't reinvent it yourself. This will be a waste of time.
I'm not sure why you think that
FileItem
only provides anOutputStream
, there's also angetInputStream()
method. Just write it to aByteArrayOutputStream
.You only need to keep in mind that this may explode your server's memory usage if there are a lot of users uploading files at the same time. Each byte of a byte array eats one byte of JVM's memory. So imagine you've 100 simultaneous users who upload each a 10MB file, then 1GB of server memory is wasted to this.
如果我理解正确的话,您只是想在 servlet 中接收通过 HTTP 上传的文件?网上有很多关于如何执行此操作的示例,例如 http:// /www.servlets.com/jservlet2/examples/ch04/UploadTest.java
我只是在你的问题中遗漏了一些东西吗?
If I understand you correctly you're just trying to receive a file uploaded over HTTP in a servlet? There are plenty of examples of how to do that on the net, e.g., http://www.servlets.com/jservlet2/examples/ch04/UploadTest.java
Am I just missing something in your question?