Reqwest: Upload progress

Created on 22 Feb 2018  路  4Comments  路  Source: seanmonstar/reqwest

Hi,

I would like to display upload progress for large files but I don't see any way to do that.
You mentionned something in #222 for download but it seems like it cannot be used for upload. Is there any plan to adding that or a secret way :smile: ?

Most helpful comment

struct UploadProgress<R> {
    inner: R,
    bytes_read: usize,
    total: usize,
}

impl<R: Read> Read for UploadProgress<R> {
    fn read(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.inner.read(buf)
            .map(|n| {
                self.bytes_read += n;
                println!("Upload progress: {}/{} bytes ({}%)", self.bytes_read, self.total, self.bytes_read * 100 / self.total);
                n
            })
    }
}

let body = UploadProgress {
    bytes_read: 0,
    total: some_number,
    inner: some_reader, // like a `File`
};

client.post(uri)
    .body(Body::sized(body, some_numer))
    .send()?;

All 4 comments

Hm, if you're streaming the upload by prodiving a Read, you could do this. I'd make a custom type that wraps your body, and implements Read. In the read function, you can read from the wrapped body, and then signal however you like that N bytes out of the total were just "sent".

@seanmonstar I tried but I really can't get my head around that. Could you make a simple example ?

struct UploadProgress<R> {
    inner: R,
    bytes_read: usize,
    total: usize,
}

impl<R: Read> Read for UploadProgress<R> {
    fn read(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.inner.read(buf)
            .map(|n| {
                self.bytes_read += n;
                println!("Upload progress: {}/{} bytes ({}%)", self.bytes_read, self.total, self.bytes_read * 100 / self.total);
                n
            })
    }
}

let body = UploadProgress {
    bytes_read: 0,
    total: some_number,
    inner: some_reader, // like a `File`
};

client.post(uri)
    .body(Body::sized(body, some_numer))
    .send()?;

Thank you, gonna try it soon :+1:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

samuela picture samuela  路  5Comments

richardanaya picture richardanaya  路  5Comments

29e7e280-0d1c-4bba-98fe-f7cd3ca7500a picture 29e7e280-0d1c-4bba-98fe-f7cd3ca7500a  路  6Comments

amesgen picture amesgen  路  6Comments

encombhat picture encombhat  路  6Comments