zanllp / sion

A single-header, cross-platform C++ library for making asynchronous HTTP(s) Requests.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

怎么上传文件到服务器?

zoujiaqing opened this issue · comments

读取文件的二进制数据保存到sion::String data,设置对应的资源类型头,使用post发送就行了。虽然很奇怪但是sion::String 真的不仅可以拿来放字符串,还可以拿来保存二进制数据。
具体资源的头可以参考 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types

应该这样就行,具体还得看后端api是怎么支持的。

除了上述,如果想一次性带上多个,也可以等我有空写个 sion::FormData (Content-Type: multipart/form-data) 来支持,(你也可自己实现在给我们提个pr,不难)这个FormData一直没用到就没实现

sion::String LoadFile(sion::String path)
{
    std::fstream file(path, std::ios_base::in);
    std::string res;
    const int size = 1000;
    std::array<char, size> buf;
    while (file.good())
    {
        file.read(&buf.at(0), size - 1);
        res.insert(res.end(), buf.begin(), buf.begin() + file.gcount());
    }
    return res;
}

int main()
{
    async_thread_pool.Start();
    auto resp = sion::Request()
        .SetUrl("http://127.0.0.1:8888")
        .SetHeader("Content-Type", "image/png")
        .SetHttpMethod(sion::Method::Post)
        .SetBody(LoadFile("checkbox.png")).Send();
    std::cout << resp.StrBody() << std::endl;
    return 1;
}

后端我用node写的,试了没什么问题

import express from 'express'
import fs from 'fs'
import bodyParser from 'body-parser';
var app = express();

app.use(bodyParser.raw({type: 'image/png', limit : '2mb'}))

app.post('/', async function(req, res) {
  // const filename = req.get('Content-Disposition')
  fs.writeFileSync('hello.png',  req.body)
  res.send('hello world');
});
app.listen(8888)

支持FormData了,主流的后端应该没有不支持这个的,参考

sion/src/main.cc

Lines 99 to 134 in 5a71200

sion::Payload::Binary LoadFile(sion::String path, sion::String type)
{
std::fstream file(path, std::ios_base::in);
sion::Payload::Binary bin;
bin.file_name = path;
bin.type = type;
const int size = 1000;
std::array<char, size> buf;
while (file.good())
{
file.read(buf.data(), size - 1);
bin.data.insert(bin.data.end(), buf.begin(), buf.begin() + file.gcount());
}
return bin;
}
void PostBinaryData()
{
auto file = LoadFile("hello.jpeg", "image/jpeg");
{
sion::Payload::FormData form;
form.Append("helo", "world");
form.Append("hello2", "world");
form.Append("file", file);
form.Append("agumi", "script runtime");
form.Remove("agumi");
auto req = sion::Request().SetUrl("http://www.httpbin.org/post").SetBody(form).SetHttpMethod("POST").Send();
std::cout << "post binary data with FormData " << req.Code() << req.StrBody();
}
{
auto req = sion::Request().SetUrl("http://www.httpbin.org/post").SetBody(file).SetHttpMethod("POST").Send();
std::cout << "post binary data with Binary " << req.Code() << req.StrBody();
}
}