Home >Backend Development >C++ >Can I Get a Remote File's Size Using HTTP Headers?
Query:
It is desirable to retrieve the size of a remote file hosted at an HTTP endpoint before initiating the download. Is it feasible to leverage HTTP headers to achieve this, and if so, how can the HTTP header for a specific file be accessed to obtain its size?
Solution:
Most HTTP servers provide a mechanism to retrieve file metadata, including size, without transferring the entire file. This is known as the HEAD method. Here's how to retrieve the file size from HTTP headers using the HEAD method in C#:
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; }
Caveat:
While most servers support the HEAD method, some may not allow it or may omit the "Content-Length" header in their response. In such cases, it may be necessary to download the file to determine its size. However, many servers provide this information for convenience.
The above is the detailed content of Can I Get a Remote File's Size Using HTTP Headers?. For more information, please follow other related articles on the PHP Chinese website!