![](/img/trans.png)
[英]How to download a zip file from github repo and read her content in memory?
[英]How to download a zip file from a github repo using libcurl?
I have upload a zip
file compressed with WinRAR containing a txt file into my github test Repo , how I could download the zip
file using curl
?
我试过了:
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
void Download(std::string url)
{
CURL *curl_handle;
static const char *pagefilename = "data.zip";
FILE *pagefile;
curl_global_init(CURL_GLOBAL_ALL);
/* init the curl session */
curl_handle = curl_easy_init();
/* set URL to get here */
curl_easy_setopt(curl_handle, CURLOPT_URL, url.c_str());
/* Switch on full protocol/debug output while testing */
curl_easy_setopt(curl_handle, CURLOPT_VERBOSE, 1L);
/* disable progress meter, set to 0L to enable and disable debug output */
curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L);
/* send all data to this function */
curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);
/* open the file */
pagefile = fopen(pagefilename, "wb");
if(pagefile) {
/* write the page body to this file handle */
curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, pagefile);
/* get it! */
CURLCode res;
res = curl_easy_perform(curl_handle);
/* close the header file */
fclose(pagefile);
}
/* cleanup curl stuff */
curl_easy_cleanup(curl_handle);
curl_global_cleanup();
return;
}
Download("https://github.com/R3uan3/test/files/9544940/test.zip");
CURLCode res
返回 (CURLE_OK) 但它创建了一个文件data.zip
of 0 bytes
,怎么了?
我检查过
curl -I https://github.com/R3uan3/test/files/9544940/test.zip
它得到
HTTP/2 302
...
location: https://objects.githubusercontent.com/github-production-rep...
换句话说:这是一个重定向,您没有要求 libcurl 遵循重定向 - 所以您只会存储第一个响应(它的正文为零字节)。
您可以通过将此行添加到代码中来使 libcurl 遵循重定向:
curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.