官网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;
}