帮我用C++写一段代码用户可以选择一个本地图片作为头像上传至服务器
时间: 2023-06-01 07:05:14 浏览: 60
好的,以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <curl/curl.h>
#define UPLOAD_URL "http://example.com/upload"
int main()
{
char *filename = NULL;
char *postname = NULL;
FILE *fp = NULL;
struct stat fileinfo;
CURL *curl = NULL;
CURLcode res;
struct curl_httppost *formpost = NULL;
struct curl_httppost *lastptr = NULL;
// 获取本地图片文件名
filename = (char *)malloc(256);
printf("Please input image filename: ");
scanf("%s", filename);
// 打开本地图片文件
fp = fopen(filename, "rb");
if (fp == NULL) {
printf("Open file failed: %s\n", filename);
goto error;
}
// 获取本地图片文件信息
if (fstat(fileno(fp), &fileinfo) != 0) {
printf("Get file info failed: %s\n", filename);
goto error;
}
// 构造POST请求
curl_formadd(&formpost, &lastptr,
CURLFORM_COPYNAME, "userfile",
CURLFORM_FILENAME, filename,
CURLFORM_STREAM, fp,
CURLFORM_CONTENTTYPE, "image/jpeg",
CURLFORM_END);
// 初始化CURL库
curl = curl_easy_init();
if (curl == NULL) {
printf("Init CURL failed\n");
goto error;
}
// 设置上传URL
curl_easy_setopt(curl, CURLOPT_URL, UPLOAD_URL);
// 设置POST数据
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
// 执行HTTP请求
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
printf("Upload failed: %s\n", curl_easy_strerror(res));
goto error;
}
// 释放资源
curl_formfree(formpost);
curl_easy_cleanup(curl);
free(filename);
fclose(fp);
printf("Upload success!\n");
return 0;
error:
if (formpost != NULL) {
curl_formfree(formpost);
}
if (curl != NULL) {
curl_easy_cleanup(curl);
}
if (filename != NULL) {
free(filename);
}
if (fp != NULL) {
fclose(fp);
}
return -1;
}