【问题标题】:Upload files to Google Drive via HTTP request (C)通过 HTTP 请求将文件上传到 Google Drive (C)
【发布时间】:2019-04-15 06:12:52
【问题描述】:

我想使用 C 编程将文件上传到 Google Drive。

我遵循了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);

谢谢!

【问题讨论】:

  • @ybungalobill 嗨,但是如果我要上传图片,如何输入图片的内容?

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


【解决方案1】:

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

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

【讨论】:

  • 嗨,我不太明白如何输入照片的确切内容
  • @VanessaLeung:您无需“输入”它,而是通过回调读取并发送它,如链接示例中所示
【解决方案2】:

将图像视为常规字节。 Content-Type 将告诉特定解析器附加在帖子正文中的字节代表什么。毕竟它都是一和零。只要满足 http 请求响应结构,您无需负责将数据分块并发送。协议是标题中每个字段的合同(在跳过的行之前),提供有关您的实际数据的元数据。一旦必要的信息(长度,类型,...)符合要求,只需将图像作为常规字节读取并附加到消息中。剩下的就是http(tcp/ip)的问题了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多