如何将传入流写入 warp 文件?
How to write incoming stream into a file in warp?
目标:
服务器应该能够接收二进制数据流并将其保存到文件中。
我收到此错误:
mismatched types
expected `&[u8]`, found type parameter `B`
如何从通用类型 B
中获取 &[u8]
?
use warp::Filter;
use warp::{body};
use futures::stream::Stream;
async fn handle_upload<S, B>(stream: S) -> Result<impl warp::Reply, warp::Rejection>
where
S: Stream<Item = Result<B, warp::Error>>,
S: StreamExt,
B: warp::Buf
{
let mut file = File::create("some_binary_file").unwrap();
let pinnedStream = Box::pin(stream);
while let Some(item) = pinnedStream.next().await {
let data = item.unwrap();
file.write_all(data);
}
Ok(warp::reply())
}
#[tokio::main]
async fn main() {
pretty_env_logger::init();
let upload = warp::put()
.and(warp::path("stream"))
.and(body::stream())
.and_then(handle_upload);
warp::serve(upload).run(([127, 0, 0, 1], 3030)).await;
}
B
实现 warp::Buf
,它是 bytes crate 的 re-exported。它有一个 .bytes()
方法 return 是一个 &[u8]
可能有效。
但是,文档说 .bytes()
可能 return 比它实际包含的内容更短。因此,您可以在 .has_remaining()
时调用 .bytes()
和 .advance()
流,或者将其转换为 Bytes
并将其发送到文件:
let mut data = item.unwrap();
file.write_all(data.to_bytes().as_ref());
目标:
服务器应该能够接收二进制数据流并将其保存到文件中。
我收到此错误:
mismatched types
expected `&[u8]`, found type parameter `B`
如何从通用类型 B
中获取 &[u8]
?
use warp::Filter;
use warp::{body};
use futures::stream::Stream;
async fn handle_upload<S, B>(stream: S) -> Result<impl warp::Reply, warp::Rejection>
where
S: Stream<Item = Result<B, warp::Error>>,
S: StreamExt,
B: warp::Buf
{
let mut file = File::create("some_binary_file").unwrap();
let pinnedStream = Box::pin(stream);
while let Some(item) = pinnedStream.next().await {
let data = item.unwrap();
file.write_all(data);
}
Ok(warp::reply())
}
#[tokio::main]
async fn main() {
pretty_env_logger::init();
let upload = warp::put()
.and(warp::path("stream"))
.and(body::stream())
.and_then(handle_upload);
warp::serve(upload).run(([127, 0, 0, 1], 3030)).await;
}
B
实现 warp::Buf
,它是 bytes crate 的 re-exported。它有一个 .bytes()
方法 return 是一个 &[u8]
可能有效。
但是,文档说 .bytes()
可能 return 比它实际包含的内容更短。因此,您可以在 .has_remaining()
时调用 .bytes()
和 .advance()
流,或者将其转换为 Bytes
并将其发送到文件:
let mut data = item.unwrap();
file.write_all(data.to_bytes().as_ref());