使用 reqwest 发送附件
Sending attachment with reqwest
我正在尝试使用 reqwest
执行 POST 请求。我需要在请求中发送附件。我正在寻找
的等价物
curl -F attachment=@file.txt
在旧版本中(参见 here)它就像
一样简单
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()?;
但对于较新的版本(参见 here),该功能似乎已被删除。我收到错误:
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`
The basic one is by using the body()
method of a RequestBuilder
. This lets you set the exact raw bytes of what the body should be. It accepts various types, including String
, Vec<u8>
, and File
.
新的 API 可能不再为 Body
实现 From<File>
但确实为 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()?;
我正在尝试使用 reqwest
执行 POST 请求。我需要在请求中发送附件。我正在寻找
curl -F attachment=@file.txt
在旧版本中(参见 here)它就像
一样简单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()?;
但对于较新的版本(参见 here),该功能似乎已被删除。我收到错误:
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`
The basic one is by using the
body()
method of aRequestBuilder
. This lets you set the exact raw bytes of what the body should be. It accepts various types, includingString
,Vec<u8>
, andFile
.
新的 API 可能不再为 Body
实现 From<File>
但确实为 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()?;