c++ http 图片上传
时间: 2023-10-10 07:05:08 浏览: 37
要实现http图片上传,可以使用c++的libcurl库。以下是一个简单的示例代码:
```cpp
#include <curl/curl.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
size_t write_callback(char* ptr, size_t size, size_t nmemb, void* userdata)
{
return fwrite(ptr, size, nmemb, (FILE*)userdata);
}
int main(int argc, char** argv)
{
CURL* curl;
CURLcode res;
struct curl_httppost* formpost = NULL;
struct curl_httppost* lastptr = NULL;
struct curl_slist* headerlist = NULL;
static const char buf[] = "Expect:";
string filename = "test.jpg";
curl_global_init(CURL_GLOBAL_ALL);
/* Fill in the file upload field */
curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "file", CURLFORM_FILE, filename.c_str(), CURLFORM_END);
/* Fill in the submit field too, even if this is rarely needed */
curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "submit", CURLFORM_COPYCONTENTS, "Upload", CURLFORM_END);
/* initialize custom header list (stating that Expect: 100-continue is not wanted */
headerlist = curl_slist_append(headerlist, buf);
/* Create a curl handle */
curl = curl_easy_init();
/* set the form post values */
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
/* specify URL to upload to */
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/upload");
/* set custom set of headers */
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
/* send request & get response */
res = curl_easy_perform(curl);
/* cleanup */
curl_easy_cleanup(curl);
/* free form post */
curl_formfree(formpost);
/* free slist */
curl_slist_free_all(headerlist);
return 0;
}
```
在上面的代码中,我们使用了`curl_formadd`函数来填充上传的文件和字段,使用`curl_slist_append`函数来填充自定义的HTTP头,最后使用`curl_easy_perform`函数来发送请求并接收响应。
需要注意的是,上传的文件路径需要使用绝对路径,并且需要在编译时链接curl库。