http实现客户端上传数据、上传文件、下载文件

1.依赖库 cpp-httplib nlohmann-json
在QT Cmake工程中引入vcpkg
参考:https://blog.csdn.net/zdx135/article/details/130640851

修改vcpkg.json
{
“name”: “entension-packages”,
“version-string”: “0.1.0”,
“dependencies”: [
“spdlog”,
“cpp-httplib”,
“nlohmann-json”
]
}
2. 上传数据接口 http://47.116.128.228:10105/monitors
上传文件接口 http://47.116.128.228:10105/monitors/10086/lcr_file
下载文件路径 http://fcs.audfly.tech/storage/lcrs/10086.lcr
上传数据内容
{
“oem_sn”:“123”, //字符串
“spl_value”: 0.1, //float
“datas”:[0.1,0.2] //数组
}

#include <nlohmann/json.hpp>
#include <httplib.h>
using json = nlohmann::json;
std::shared_ptr<httplib::Client> client_ = std::make_shared<httplib::Client>("47.116.128.228", 10105);
json j;
j["oem_sn"] = "123";
j["spl_value"] = 0.1;
json arr = json::array();
arr.push(0.1);
arr.push(0.2);
j["datas"] = arr;
std::string json_str = j.dump();
//上传数据
auto res_data = client_->Post("/monitors", json_str, "application/json");

if(res_data && res_data ->status == 200)
{
	std::cout << "数据上传成功" << res_data ->body << std::endl;
}

//上传文件
std::string file_content = "";   //上传文件路径
// 读取上传文件的内容
std::ifstream data_file(file_content, std::ios::binary);
if (data_file.fail()) {
     return;
 }
 std::ostringstream oss;
 oss << data_file.rdbuf();
 std::string content = oss.str();
 data_file.close();
 // 设置传输头 lcr_file是key值  最后有postman的上传设置图片方便理解
httplib::MultipartFormDataItems items = {{"lcr_file", content, file_content, "application/octet-stream"}};
client_->set_read_timeout(200);
QString post_des = "/monitors/10086/lcr_file";
httplib::Result res_file = client_->Post(post_des.toStdString().c_str(), items);
if(res_file && res_file ->status == 200)
{
	std::cout << "文件上传成功" << res_file ->body << std::endl;
}

//下载文件
std::string download_file_name = ""; //设置下载文件路径
// 开始下载文件
std::string get_url = "/storage/lcrs/10086.lcr";
std::ofstream ofs(download_file_name, std::ios::binary | std::ios::trunc);
httplib::Client cli("http://fcs.audfly.tech");
auto download_res = cli.Get(get_url.c_str(), [&](const char* data, size_t data_length) {
    string_view view(data, data_length);
    ofs << view;
    return true;
});
if (download_res) {
    std::cout << "download_res status ==== " << download_res->status << std::endl;
}
ofs.close();

在这里插入图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值