Created
September 7, 2019 10:56
-
-
Save mexus/f78351095f7dce8bae8907fdbafa9e93 to your computer and use it in GitHub Desktop.
Converts a file into reqwest::async::multipart::Part
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use bytes::{Bytes, BytesMut}; | |
use reqwest::r#async::multipart::Part; | |
use std::{io, path::Path}; | |
use tokio::{ | |
codec::{Decoder, FramedRead}, | |
prelude::*, | |
}; | |
struct FileCodec; | |
impl Decoder for FileCodec { | |
type Item = Bytes; | |
type Error = io::Error; | |
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { | |
Ok(Some(src.take().freeze())) | |
} | |
} | |
fn file_to_chunks<P>(path: P) -> impl Stream<Item = Bytes, Error = io::Error> | |
where | |
P: AsRef<Path> + Send + 'static, | |
{ | |
tokio::fs::File::open(path) | |
.map(|file| FramedRead::new(file, FileCodec)) | |
.flatten_stream() | |
} | |
pub fn file_to_part<P>(path: P) -> Part | |
where | |
P: AsRef<Path> + Send + 'static, | |
{ | |
Part::stream(file_to_chunks(path)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment