首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用reqwest发送附件

用reqwest发送附件
EN

Stack Overflow用户
提问于 2021-02-14 11:20:05
回答 1查看 231关注 0票数 1

我正在尝试使用reqwest进行一个POST请求。我需要在请求中发送附件。我要找的是相当于

代码语言:javascript
复制
curl -F attachment=@file.txt

在旧版本(请参阅这里)中,它非常简单

代码语言:javascript
复制
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()?;

但是对于更新的版本(请参阅这里),该功能看起来已经被删除了。我知道错误:

代码语言:javascript
复制
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方法。这允许您设置主体应该是什么的确切的原始字节。它接受各种类型,包括StringVec<u8>File

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-14 11:39:25

新的API可能不再为Body实现Body,而是为Body实现了From<Vec<u8>>,我们可以轻松地将File转换为Vec<u8>

实际上,标准库中已经有一个名为std::fs::read的方便的函数,它将读取整个文件并将其存储在Vec<u8>中。下面是更新的工作示例:

代码语言:javascript
复制
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()?;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66194878

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档