Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the length of a file without downloading the file in a cURL binary get request

Tags:

c++

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?

like image 231
rturrado Avatar asked Feb 02 '23 13:02

rturrado


2 Answers

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.

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.

like image 92
Remy Lebeau Avatar answered Feb 06 '23 16:02

Remy Lebeau


Have you tried with CURLINFO_CONTENT_LENGTH_DOWNLOAD instead?

like image 42
crazyjul Avatar answered Feb 06 '23 14:02

crazyjul