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?
相关问题
- Angular RxJS mergeMap types
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Yes, assuming the HTTP server you're talking to supports/allows this:
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.
Yes, this is the way to go. If the information is provided, it's in the header as the
Content-Length
. Note, however, that this is not necessarily the case.Downloading only the header can be done using a
HEAD
request instead ofGET
. Maybe the following code helps:Notice the property for the content length on the
HttpWebResponse
object – no need to parse theContent-Length
header manually.Note that not every server accepts
HTTP HEAD
requests. One alternative approach to get the file size is to make anHTTP GET
call to the server requesting only a portion of the file to keep the response small and retrieve the file size from the metadata that is returned as part of the response content header.The standard
System.Net.Http.HttpClient
can be used to accomplish this. The partial content is requested by setting a byte range on the request message header as:The server responds with a message containing the requested range as well as the entire file size. This information is returned in the response content header (
response.Content.Header
) with the key "Content-Range".Here's an example of the content range in the response message content header:
In this example the header value implies the response contains bytes 0 to 15 (i.e., 16 bytes total) and the file is 2,328,372 bytes in its entirety.
Here's a sample implementation of this method: