怎么上传文件到服务器?
zoujiaqing opened this issue · comments
zoujiaqing commented
zanllp commented
读取文件的二进制数据保存到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一直没用到就没实现
zanllp commented
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)