2

目标:

服务器应该能够接收二进制数据流并将其保存到文件中。

我收到此错误:

mismatched types

expected `&[u8]`, found type parameter `B`

我怎样才能&[u8]从泛型类型中获得一个B

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;
}
4

1 回答 1

0

B从字节 cratewarp::Buf重新导出的实现。它有一个方法可以返回一个可以工作的方法。.bytes()&[u8]

但是,文档说这.bytes()可能会返回比它实际包含的更短的切片。因此,您可以在流的同时调用它.bytes()或将其转换为并将其发送到文件:.advance().has_remaining()Bytes

let mut data = item.unwrap();
file.write_all(data.to_bytes().as_ref());
于 2020-10-24T18:05:10.220 回答