URL连接和内容长度:下载了多少数据?
我创建了一个 servlet,它将文件的内容读取到字节数组,随后将其写入响应的 OutputStream:
// set headers
resp.setHeader("Content-Disposition","attachment; filename=\"file.txt\"");
resp.setHeader("Content-Length", "" + fileSize);
// output file content.
OutputStream out = resp.getOutputStream();
out.write(fileBytes);
out.close();
现在,我还编写了一个“客户端”,它需要找出文件有多大。这应该很容易,因为我添加了“Content-Length”标头。
URLConnection conn = url.openConnection();
long fileSize = conn.getContentLength();
然而,我对整体情况有点不确定。据我了解我自己的 servlet,整个文件内容都被转储到响应的 OutputStream 中。但是,调用 getContentLength() 是否也会导致实际文件数据以某种方式部分或全部下载?换句话说,当我调用 conn.getContentLength() 时,将从服务器返回多少文件?标题是否与内容“分开”?
所有的输入都受到高度赞赏!
I've created a servlet which reads the content of a file to a byte array which subsequently is written to the OutputStream of the response:
// set headers
resp.setHeader("Content-Disposition","attachment; filename=\"file.txt\"");
resp.setHeader("Content-Length", "" + fileSize);
// output file content.
OutputStream out = resp.getOutputStream();
out.write(fileBytes);
out.close();
Now, I've also written a "client" which needs to find out how big the file is. This should be easy enough as I've added the "Content-Length" header.
URLConnection conn = url.openConnection();
long fileSize = conn.getContentLength();
However, I am a little uncertain about the big picture. As I understand my own servlet, the entire file content is dumped to the OutputStream of the response. However, does calling getContentLength() also result in the actual file data somehow partially or fully being downloaded? In other words, when i invoke conn.getContentLength(), how much of the file will be returned from the server? Does the headers come "separate" from the content?
All input highly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,
getContentLength()
方法仅以整数形式返回内容大小的字符串值。不会下载任何文件。
是的,标题与内容“分开”。
现在你确定了:D
No, the
getContentLength()
method just returns a String value of the size of the content as an Integer.None of the file will be downloaded.
Yes, the headers come "separate" from the content.
Now you're certain :D
请参阅 javadocs
因此,调用
getContentLength()
仅读取标头值,不会导致任何下载。您必须为此调用getContent()
。See the javadocs
So a call to
getContentLength()
merely reads the header value and does not cause any downloading. You have to callgetContent()
for that.