如何在 cURL 二进制 get 请求中获取文件的长度而不下载文件
我想在一些 C++ 代码中创建一个 cURL 请求,该请求将在不下载文件的情况下获取服务器中文件的长度。为此,我使用一些 cURL 选项来告诉我只需要请求响应中的标头,然后检查响应以获取文件长度。
我设置以下请求选项:
curl_easy_setopt(_curl_handle, CURLOPT_HEADER, 1);
curl_easy_setopt(_curl_handle, CURLOPT_NOBODY, 1);
然后处理请求,等待响应,该响应显示 OK=200
,最后查询文件长度:
curl_easy_getinfo(_curl_handle, CURLINFO_CONTENT_LENGTH_UPLOAD, &dResult);
但我得到的文件长度为 -1
。根据 cURL 文档,这意味着大小未知。怎么会出现cURL没有从服务器获取文件长度信息呢?
I want to create a cURL request in some C++ code which will get me the length of a file in a server without downloading the file. For that, I use some cURL options to tell I only want headers in the request response, and then I examine the response to get the file length.
I'm setting the following request options:
curl_easy_setopt(_curl_handle, CURLOPT_HEADER, 1);
curl_easy_setopt(_curl_handle, CURLOPT_NOBODY, 1);
Then processing the request, waiting for the response, which shows a OK=200
, and finally enquiring about the file length:
curl_easy_getinfo(_curl_handle, CURLINFO_CONTENT_LENGTH_UPLOAD, &dResult);
But I get a file length of -1
. According to cURL documentation, that means size is unknown. How can it happen that cURL doesn't get the file length information from the server?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
CURLINFO_CONTENT_LENGTH_UPLOAD
是上传的字节数。您需要改用CURLINFO_CONTENT_LENGTH_DOWNLOAD
。请注意,如果服务器动态生成数据,则实际下载文件时的长度与仅下载其标头时的长度可能会有所不同。
另请注意,如果服务器在下载时发送压缩数据,则标头中可能没有任何可用大小(如果使用
Transfer-Encoding
标头而不是Content-Length
code> 标头),因此CURLINFO_CONTENT_LENGTH_DOWNLOAD
仍会返回-1
。在这种情况下,了解其大小的唯一方法是完整下载它。CURLINFO_CONTENT_LENGTH_UPLOAD
is the number of bytes uploaded. You need to useCURLINFO_CONTENT_LENGTH_DOWNLOAD
instead.Note that if the server dynamically generates the data, the length may be different when you actualy download the file versus just downloading its headers.
Also note that if the server sends data as compressed when downloaded, there may not be any size available in the headers (if the
Transfer-Encoding
header is used instead of theContent-Length
header), soCURLINFO_CONTENT_LENGTH_DOWNLOAD
would still return-1
. The only way to know the size in that situation would be to download it in full.您是否尝试过使用
CURLINFO_CONTENT_LENGTH_DOWNLOAD
?Have you tried with
CURLINFO_CONTENT_LENGTH_DOWNLOAD
instead?需要调用
perform()
curl_easy_perform(_curl_handle);
need call
perform()
curl_easy_perform(_curl_handle);