Skip to content

Instantly share code, notes, and snippets.

@mexus
Created September 7, 2019 10:56
Show Gist options
  • Save mexus/f78351095f7dce8bae8907fdbafa9e93 to your computer and use it in GitHub Desktop.
Save mexus/f78351095f7dce8bae8907fdbafa9e93 to your computer and use it in GitHub Desktop.
Converts a file into reqwest::async::multipart::Part
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