我想在下载之前获取 http:/.../file 的大小.该文件可以是网页、图像或媒体文件.这可以用 HTTP 标头完成吗?如何只下载文件 HTTP 标头?
I want to get the size of an http:/.../file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header?
是的,假设您正在与之交谈的 HTTP 服务器支持/允许:
Yes, assuming the HTTP server you're talking to supports/allows this:
public long GetFileSize(string url)
{
long result = -1;
System.Net.WebRequest req = System.Net.WebRequest.Create(url);
req.Method = "HEAD";
using (System.Net.WebResponse resp = req.GetResponse())
{
if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength))
{
result = ContentLength;
}
}
return result;
}
如果不允许使用 HEAD 方法,或者服务器回复中不存在 Content-Length 标头,则确定服务器上内容大小的唯一方法是下载它.由于这不是特别可靠,因此大多数服务器都会包含此信息.
If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information.
这篇关于如何从 http 标头获取文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!