上传后curl_easy_getinfo没有返回正确的大小

时间:2016-12-26 11:19:16

标签: c++ curl

我有以下代码

#include <stdio.h>
#include <curl/curl.h>
#include <iostream>
using namespace std;

size_t read_file_data(char* buffer, size_t size,
                      size_t nitems, void* instream) {
    printf("\nUpload file binary data");
    cout << "Read" << nitems << " items by " << size << " bytes" << endl;

    size_t retcode = fread(buffer, size, nitems,
                           static_cast<FILE*>(instream));
    size_t retsize = size * retcode;
    cout << "Read " << retsize << "bytes from file\n";
    return retsize;
}

int main(void)
{
    CURL* curl = curl_easy_init();
    if (!curl) {
      return 1;
    }
    curl_easy_setopt(curl, CURLOPT_URL, "http://172.30.191.145:3000/upload");

    struct curl_slist* chunk = NULL;
    chunk = curl_slist_append(chunk, "Transfer-Encoding: chunked");
    chunk = curl_slist_append(chunk,
                              "Content-type:application/octet-stream");
    chunk = curl_slist_append(chunk, "Session: test");
    CURLcode result = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
    FILE* fp = 
        fopen("/home/thinh/Documents/SDL/curlupload/testfile.txt","rb");

    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_READFUNCTION,
                     &read_file_data);
    curl_easy_setopt(curl, CURLOPT_READDATA, fp);

    result = curl_easy_perform(curl);
    cout << "curl result " << result << endl;

    CURLcode get_info_result;
    double val = 0;
    get_info_result = curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &val);
    if (CURLE_OK == get_info_result) {
      printf("Size of uploaded data:  %0.0f bytes.\n", val);
    } else {
      printf("ERROR");
    }

    curl_easy_cleanup(curl);
    curl_slist_free_all(chunk);
    fclose(fp);

    return 0;
}

执行后,上传数据的大小始终大于实际文件大小。 但上传到服务器后的文件是正确的(与本地文件相同) 我使用ll command来检查文件大小

这一行的问题

get_info_result = curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &val);

例如:我上传本地文件text.txt 1022字节,但在日志中:&#34;上传数据的大小:1034字节。&#34;,在服务器中它是1022字节。 text.txt内容:

  

abcd123   abcd123   abcd123

我无法找到有关上传文件大小的任何文档谈话详情。

1 个答案:

答案 0 :(得分:0)

更改此行后:

chunk = curl_slist_append(chunk, "Transfer-Encoding: chunked");

chunk = curl_slist_append(chunk, "Transfer-Encoding: ");

我在日志中获得了正确的大小。 分块编码修改消息正文,以便将其作为一系列块传输,每个块都有自己的大小指示符,后跟包含实体标题字段Ref的可选预告片。

但我必须使用chunked。有没有办法获得正确的上传数据