1.libcurl功能简介
https://curl.se/libcurl/
具体使用方法可以看这里的简介:https://www.cnblogs.com/heluan/p/10177475.html
2.上传文件到ftp上
具体见代码:
#include <string>
namespace BaseFun
{
struct UploadFileSession
{
static bool UploadFile(std::string& response, const std::string& file_name, const std::string& url, const string& aut);
};
}
#include "curl/curl.h"
#include <string>
#include<UploadFileSession.h>
using namespace std;
size_t WriteToString(void *buffer, size_t size, size_t nmemb, void *userp)
{
(*((std::string*)userp)).append((char*)buffer, size * nmemb);
return size * nmemb;
}
namespace BaseFun
{
bool UploadFileSession::UploadFile(std::string& response, const std::string& file_name, const std::string& url, const string& aut)
{
CURL* curl_handle_ = curl_easy_init();
// 重置参数
curl_easy_reset(curl_handle_);
// 设置http请求行
curl_easy_setopt(curl_handle_, CURLOPT_URL, url.c_str());
// 设置http头
struct curl_slist* headers = NULL;
string authorization = "Authorization: " + aut;
headers = curl_slist_append(headers, authorization.c_str());
curl_easy_setopt(curl_handle_, CURLOPT_HTTPHEADER, headers);
// 设置https选项
curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl_handle_, CURLOPT_SSL_VERIFYHOST, false);
//设置回调函数
curl_easy_setopt(curl_handle_, CURLOPT_WRITEFUNCTION, WriteToString);
curl_easy_setopt(curl_handle_, CURLOPT_WRITEDATA, &response);
curl_easy_setopt(curl_handle_, CURLOPT_CONNECTTIMEOUT, 6L);
curl_easy_setopt(curl_handle_, CURLOPT_TIMEOUT, 10L);
// 设置表单数据
struct curl_httppost* post = NULL;
struct curl_httppost* last = NULL;
curl_formadd(
&post, &last,
CURLFORM_COPYNAME, "file",
CURLFORM_FILE, file_name.c_str(),
CURLFORM_FILENAME, file_name.c_str(),
CURLFORM_END);
curl_easy_setopt(curl_handle_, CURLOPT_HTTPPOST, post);
int rsp_code = 0;
CURLcode res = curl_easy_perform(curl_handle_);
if (res == CURLE_OK)
{
curl_easy_getinfo(curl_handle_, CURLINFO_RESPONSE_CODE, &rsp_code);
}
else
{
LOG_ERROR( "upload failed, errorcode = %d, res = %d, resmessage = %s", rsp_code, res, response.c_str());
}
curl_formfree(post);
curl_slist_free_all(headers);
return res == CURLE_OK ? true : false;
}
}
//测试用例
#include <stdio.h>
#include <iostream>
#include <stdarg.h>
#include<UploadFileSession.h>
using namespace std;
char* str_fmt(const char* lpFormat, ...)
{
static char buff[1024 * 10];
va_list ap;
va_start(ap, lpFormat);
vsprintf(buff, lpFormat, ap);
va_end(ap);
return buff;
}
int main(int argc, char *argv[])
{
std::string ip;
int port;
string address = str_fmt("https://%s:%d", ip.c_str(), port);
string url = address + "/api/v1/upload";
string csr_path = "audiofile/" + k_csr;
string api_key_; // 验证成功后获取到的,这个认证的key
string resp;
if(!BaseFun::UploadFileSession::UploadFile(resp, csr_path, url, api_key_))
{
return false;
}
return 0;
}