首页 > 解决方案 > 如何使用 libcurl 获取文件名?

问题描述

libcurl用来下载文件,url可能是下面这样

url = "https://***.com/**/***/abc"
url = "http://***:8000/**/test.txt?***2484d197c16b2e"
url = "http://***:8000/**/test.txt"

获取它的文件名很麻烦,那么有没有办法libcurl在下载时使用它来获取文件名?我的下载代码如下。

size_t writeData(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int downloadFile(const char *url, const char *saveFile)
{
    CURL *curl;
    FILE *saveFd;
    CURLcode res;
   
    curl = curl_easy_init();
    if (curl) {
        saveFd = fopen(saveFile,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeData);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, saveFd);
        std::string strurl = string(url);
        if (strurl.find("https") != string::npos) {
            curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        
        fclose(saveFd);
    }
    return 0;
}

标签: c++libcurl

解决方案


用于CURLOPT_HEADERFUNCTION获取每个 HTTP 标头的回调。您正在寻找名为Content-Disposition.


推荐阅读