Eugeny89
Eugeny89

Reputation: 3741

uploading file with libcurl

Take a look at the following code

static size_t reader(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t retcode = fread(ptr, size, nmemb, stream);
    cout << "*** We read " << retcode << " bytes from file" << endl;
    return retcode;
}

void upload() { //upload() is called from ouside
    FILE *pFile;
    pFile = fopen("map.txt" , "r");

    struct stat file_info;
    stat("map.txt", &file_info);
    size_t size = (size_t)file_info.st_size;
    uploadFile(pFile, size);
}

bool uploadFile(void* data, size_t datasize) {
    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();
    if (curl) {
        char *post_params = ...;
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_params);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) strlen(post_params));
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, reader);
        curl_easy_setopt(curl, CURLOPT_READDATA, data);
        curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t) datasize);

        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }
    return true;
}

When the code is executed, the following is outputed

*** We read 490 bytes from file
*** We read 0 bytes from file

after that the app does nothing (even not exiting).

Can someone point out at what's wrong here?

Will be grateful for any help!!!

Upvotes: 1

Views: 8065

Answers (1)

Daniel Stenberg
Daniel Stenberg

Reputation: 58164

There's some serious confusions shown in this code. Let me try to explain:

CURLOPT_UPLOAD - this will ask libcurl to PUT the file when the protocol of choice is HTTP

CURLOPT_POSTFIELDS - tells libcurl to POST the data that is provided in the additional argument (which has the size set with CURLOPT_POSTFIELDSIZE)

CURLOPT_READFUNCTION - provides libcurl an alternative way to get data than CURLOPT_POSTFIELDS to allow a POST that reads the data from a file. When using CURLOPT_UPLOAD this is the only way to provide data.

So in the end the questions left for you are:

  • Do you want PUT or POST?

  • Do you want to provide the data as a string or do you want it provided with a callback?

Upvotes: 7

Related Questions