c++ http 图片上传
时间: 2023-10-10 17:04:23 浏览: 40
要在 C++ 中进行 HTTP 图片上传,你需要使用一些第三方库,比如 cURL。cURL 是一个用于传输数据的开源库,支持多种协议,包括 HTTP 和 HTTPS。
以下是一个基本的 HTTP 图片上传示例代码,使用了 cURL:
```c++
#include <curl/curl.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// 读取图片数据
ifstream infile("image.jpg");
string image_data((istreambuf_iterator<char>(infile)), (istreambuf_iterator<char>()));
infile.close();
// 初始化 cURL
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (curl) {
// 设置请求 URL
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/upload");
// 设置请求方法为 POST
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 设置请求头
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: image/jpeg");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// 设置请求体为图片数据
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, image_data.c_str());
// 执行请求
res = curl_easy_perform(curl);
// 检查请求结果
if (res != CURLE_OK) {
cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
}
// 清理 cURL
curl_easy_cleanup(curl);
}
return 0;
}
```
该示例代码将图片数据读取到字符串中,然后使用 cURL 发送 POST 请求,将图片数据作为请求体发送到指定的 URL。在请求头中设置了 Content-Type 为 image/jpeg,以便服务器正确解析图片数据。需要注意的是,该示例代码中使用了 C++11 的字符串迭代器,因此需要编译器支持 C++11。