如何获取文件的长度,而无需在cURL二进制获取请求中下载文件 [英] How to get the length of a file without downloading the file in a cURL binary get request

查看:1326
本文介绍了如何获取文件的长度,而无需在cURL二进制获取请求中下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一些C ++代码中创建一个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.

我设置以下请求选项:

curl_easy_setopt(_curl_handle, CURLOPT_HEADER, 1);
curl_easy_setopt(_curl_handle, CURLOPT_NOBODY, 1);

然后处理请求,等待响应,显示 OK = 200 ,最后查询文件长度:

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);

但我得到的文件长度为 -1 。根据cURL文档,这意味着大小是未知的。 cURL如何从服务器获取文件长度信息?

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?

推荐答案

CURLINFO_CONTENT_LENGTH_UPLOAD 是上传的字节数。您需要使用 CURLINFO_CONTENT_LENGTH_DOWNLOAD

CURLINFO_CONTENT_LENGTH_UPLOAD is the number of bytes uploaded. You need to use CURLINFO_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.

此外请注意,如果服务器在下载时发送压缩数据,那么标题可能没有任何大小(如果使用 Transfer-Encoding 头而不是 Content-Length 头),因此 CURLINFO_CONTENT_LENGTH_DOWNLOAD 仍会返回 -1 。在这种情况下,了解尺寸的唯一方法是完全下载。

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 the Content-Length header), so CURLINFO_CONTENT_LENGTH_DOWNLOAD would still return -1. The only way to know the size in that situation would be to download it in full.

这篇关于如何获取文件的长度,而无需在cURL二进制获取请求中下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆