[英]Uploading a C String using libcurl
我有一個存儲 250KB 數據的字符數組。 我想使用 libcurl 將此字符數組上傳到 S3 上的存儲桶。 我知道如何上傳文件,我可以將所有數據寫入文件並將文件發送到 S3,但這會增加不必要的額外步驟。
長話短說,如何使用 libcurl 上傳內存的特定部分?
我終於找到了解決方案並在不使用中間文件的情況下成功上傳了數據。
如果您不聲明讀取回調函數,libcurl 使用 fread,它要求您輸入文件指針作為輸入。 我發現克服這個指針問題的方法是編寫一個讀取回調函數並輸入 void 指針作為 READDATA 的輸入。 事不宜遲,這是工作代碼。 另一個重要的注意事項是您將上傳的框架集的大小。
#include <stdio.h>
#include <curl/curl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
int framesetSize = 10;
void *frameset = "0123456789";
static size_t my_read_callback(void *ptr, size_t size, size_t nmemb, void *dummy)
{
// we will ignore dummy, and pass frameset as a global parameter, along with framesetSize
size_t retcode = 0;
if (framesetSize == 0)
// we have already finished off all the data
return retcode; // initialized to 0
retcode = ( size * nmemb >= framesetSize) ? framesetSize : size * nmemb;
// set return code as the smaller of max allowed data and remaining data
framesetSize -= retcode; // adjust left amount
memcpy(ptr, frameset, retcode);
frameset += retcode ; // advance frameset pointer
return retcode;
}
int main(void)
{
CURL *curl;
CURLcode res;
double speed_upload, total_time;
curl = curl_easy_init();
if(curl) {
/* upload to this place */
curl_easy_setopt(curl, CURLOPT_READFUNCTION, my_read_callback);
curl_easy_setopt(curl, CURLOPT_URL,
"54.231.19.24/{YOURBUCKETNAME}/furkan-1.txt");
/* tell it to "upload" to the URL */
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
/* set where to read from (on Windows you need to use READFUNCTION too) */
curl_easy_setopt(curl, CURLOPT_READDATA, &frameset);
/* and give the size of the upload (optional) */
curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, framesetSize);
/* enable verbose for easier tracing */
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
}
else {
/* now extract transfer info */
curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD, &speed_upload);
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time);
fprintf(stderr, "Speed: %.3f bytes/sec during %.3f seconds\n",
speed_upload, total_time);
}
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.