官网API:https://curl.haxx.se/libcurl/c/curl_easy_setopt.html
仔细阅读API。
int upload_file(char *ilimagePath)
{
bool res = false;
int ret = 0;
printf ("line:%d upload_file start\n", __LINE__);
if (!imagePath)
{
printf("argument can't be empty\n");
return false;
}
FILE * file = fopen(imagePath, "rb");
if (file == NULL)
{
printf("%s open file failed\n", imagePath);
return false;
}
/* get file size */
struct stat fstat;
ret = stat(imagePath, &fstat);
if (ret != 0)
{
fclose(file);
printf (" %s stat file failed\n", imagePath);
return false;
}
long filesize = fstat.st_size;
struct curl_slist *headers=NULL;
CURL *curl;
char url[1024] = {0};
curl = curl_easy_init();
if (curl)
{
sprintf(url, "http://192.168.110.119:10086/image?name=%s","test");
#if 1
//设定自定义头
//前往官网查看CURLOPT_HTTPHEADER>>
headers = curl_slist_append(headers, "Host: 192.168.110.119");
headers = curl_slist_append(headers, "Content-Type: image/jpeg");
headers = curl_slist_append(headers, "Connection: Keep-Alive");
headers = curl_slist_append(headers, "Cache-Control: no-cache");
//set headers
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
#endif
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_READDATA, file);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
curl_easy_setopt(curl, CURLOPT_POST, 1L); //POST
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); //开启/关闭 打印调试详细信息模式
/* 指定图片大小,否则遇到'\0'就停止了*/
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, filesize);
printf("start send file to server\n");
CURLcode code = curl_easy_perform(curl);
if (code == CURLE_OK)
{
res = true;
}
else
{
printf("line:%d curl_easy_perform() failed: %s\n", __LINE__, curl_easy_strerror(code));
}
curl_easy_cleanup(curl);
curl_slist_free_all(headers);
}
fclose(file);
return res;
}
本文详细介绍了如何使用libcurl库实现文件的上传功能。通过具体的C语言代码示例,展示了设置HTTP头部信息、读取文件、初始化CURL句柄、设置URL、POST请求等关键步骤。同时,还涉及了文件大小的获取、错误处理及资源释放等内容。
1271

被折叠的 条评论
为什么被折叠?



