美文网首页
rust 使用reqwest实现文件上传下载

rust 使用reqwest实现文件上传下载

作者: yiang飞扬 | 来源:发表于2022-09-21 14:54 被阅读0次

依赖

reqwest是rust常用的http库,基于tokio实现,使用前先在cargo.toml文件中加入相关依赖

[dependencies]
reqwest = { version = "0.11.11", features = ["json","multipart"] } # reqwest with JSON parsing support
#futures = "0.3" # for our Async / await blocks
tokio = { version = "1.12.0", features = ["full"] }

如果http请求是multipart/form-data类型,一定要在features里面加上multipart

代码

  1. 通过mutlipart上传文件
let file_byte=std::fs::read(file_path).unwrap();
// 一定要有file_name方法,且参数不能为空,否则数据上传失败
let part=reqwest::multipart::Part::bytes(Cow::from(file_byte)).file_name("test.txt");
let form = reqwest::multipart::Form::new().part("file",part);
reqwest::Client::new()
.post(svc_url)
.multipart(form)
.send()
.await
.unwrap();
  1. 下载文件
let query_parsms=&[("arg1","value"),("arg2,value")]
reqwest::Client::new().get(svc_url).query(query_params)
.await
.unwrap()
.text()
.await
.unwrap();
  1. 通过body上传文件
let file_byte=std::fs::read(file_path).unwrap();
let body = reqwest::Body::from(file_byte));
let up_resp = reqwest::Client::new().post(svc_url)
.headers(headers)
.body(body)
.send()
.await
.unwrap();

相关文章

网友评论

      本文标题:rust 使用reqwest实现文件上传下载

      本文链接:https://www.haomeiwen.com/subject/chnbortx.html