我正在尝试使用reqwest进行一个POST请求。我需要在请求中发送附件。我要找的是相当于
curl -F attachment=@file.txt在旧版本(请参阅这里)中,它非常简单
let file = fs::File::open("much_beauty.png")?;
let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
.headers(construct_headers())
.body(file)
.send()?;但是对于更新的版本(请参阅这里),该功能看起来已经被删除了。我知道错误:
21 | .body(file)
| ^^^^ the trait `From<File>` is not implemented for `Body`
|
= help: the following implementations were found:
<Body as From<&'static [u8]>>
<Body as From<&'static str>>
<Body as From<Response>>
<Body as From<String>>
and 2 others
= note: required because of the requirements on the impl of `Into<Body>` for `File`尽管正式文件声称
基本的方法是使用
body()的RequestBuilder方法。这允许您设置主体应该是什么的确切的原始字节。它接受各种类型,包括String、Vec<u8>和File。
发布于 2021-02-14 11:39:25
新的API可能不再为Body实现Body,而是为Body实现了From<Vec<u8>>,我们可以轻松地将File转换为Vec<u8>。
实际上,标准库中已经有一个名为std::fs::read的方便的函数,它将读取整个文件并将其存储在Vec<u8>中。下面是更新的工作示例:
let byte_buf: Vec<u8> = std::fs::read("much_beauty.png")?;
let client = reqwest::Client::new();
let res = client.post("http://httpbin.org/post")
.headers(construct_headers())
.body(byte_buf)
.send()?;https://stackoverflow.com/questions/66194878
复制相似问题