c++ http 图片上传
时间: 2023-10-10 13:05:46 浏览: 38
要在 C++ 中实现 HTTP 图片上传,您需要使用一个 HTTP 库,例如 cURL。cURL 是一个非常流行的开源库,支持多种协议,包括 HTTP、HTTPS、FTP 等。
以下是一个使用 cURL 库上传图片的示例代码:
```c++
#include <curl/curl.h>
#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
CURL *curl;
CURLcode res;
// 初始化 cURL
curl_global_init(CURL_GLOBAL_ALL);
// 创建一个 cURL 句柄
curl = curl_easy_init();
if (curl) {
struct curl_httppost* post = NULL;
struct curl_httppost* last = NULL;
// 添加文件字段
curl_formadd(&post, &last, CURLFORM_COPYNAME, "file", CURLFORM_FILE, "image.jpg", CURLFORM_END);
// 添加其他字段
curl_formadd(&post, &last, CURLFORM_COPYNAME, "name", CURLFORM_COPYCONTENTS, "test", CURLFORM_END);
// 设置 URL
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/upload");
// 设置 POST 数据
curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
// 执行请求
res = curl_easy_perform(curl);
// 检查请求是否成功
if (res != CURLE_OK) {
std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
// 释放资源
curl_easy_cleanup(curl);
curl_formfree(post);
}
// 清理 cURL 全局环境
curl_global_cleanup();
return 0;
}
```
上述代码将使用 cURL 库上传名为 "image.jpg" 的图片文件,并将其作为 "file" 字段发送到 "http://example.com/upload" 地址。同时,还将添加一个名为 "name" 的文本字段,其中包含字符串 "test"。
请注意,您需要在代码中包含 cURL 头文件,并链接 cURL 库。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)