通过HTTP请求(C)将文件上传到Google云端硬盘

时间:2019-04-15 06:12:53

标签: c rest http google-drive-api libcurl

我想使用C编程将文件上传到Google云端硬盘。

我遵循以下Google's tutoriallibcurl example的说明。

POST https://www.googleapis.com/upload/drive/v3/files?uploadType=media HTTP/1.1
Content-Type: image/jpeg
Content-Length: [NUMBER_OF_BYTES_IN_FILE]
Authorization: Bearer [YOUR_AUTH_TOKEN]

[JPEG_DATA]

但是我不知道应该用[JPEG_DATA]代替什么。它是文件名吗?

对于Content-Length: [NUMBER_OF_BYTES_IN_FILE],是否意味着我应该用计算机显示的确切文件大小替换它?

我到目前为止编写的代码:

curl_handle = curl_easy_init();

struct curl_slist *header = NULL;

/* Content-Type: image/jpeg */
header = curl_slist_append(header, "Content-Type: image/jpeg");

不确定在下面的[NUMBER_OF_BYTES_IN_FILE]中放什么

/* Content-Length: [NUMBER_OF_BYTES_IN_FILE] */
header = curl_slist_append(header, "Content-Length:[NUMBER_OF_BYTES_IN_FILE]");
/* Authorization: Bearer [YOUR_AUTH_TOKEN] */
char auth[200];
strcat(auth, "Authorization: Bearer ");
strcat(auth, access_token);

header = curl_slist_append(header, auth);

curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, header);

/* POST https://www.googleapis.com/upload/drive/v3/files?uploadType=media HTTP/1.1 */
curl_easy_setopt(curl_handle, CURLOPT_URL, "https://www.googleapis.com/upload/drive/v3/files");

curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, "uploadType=media");

curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);

curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);

curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");

res = curl_easy_perform(curl_handle);

/* Print response */
if(res != CURLE_OK) {
    fprintf(stderr, "curl_easy_perform() failed: %s\n",
    curl_easy_strerror(res4));
}

else {
    printf("%s\n", chunk.memory);
}

curl_easy_cleanup(curl_handle);

free(chunk.memory);

谢谢!

1 个答案:

答案 0 :(得分:2)

[JPEG_DATA]是文件的确切内容,一个字节一个字节。 [NUMBER_OF_BYTES_IN_FILE]是文件的大小,巧合的是[JPEG_DATA]中的字节数。

您可以看到post-callback.c来了解如何向POST请求中添加有效负载,以及httpput.c来了解如何从文件中增量读取数据。