reqwest icon indicating copy to clipboard operation
reqwest copied to clipboard

How best to set mime type on file Part?

Open rogusdev opened this issue 1 year ago • 0 comments

What is the recommend way to set a mime type on a multipart file Part, given that it might fail? The fact that there is no try_mime or something means that I when build a Part and attempt to set its mime type, I then might need to completely rebuild it, e.g.:

let mut part = Part::bytes(bytes.clone()).file_name(filename.clone());
if let Some(mime_type) = mime_guess::from_path(filename.clone()).first_raw() {
    match part.mime_str(mime_type) {
        Ok(part2) => part = part2,
        Err(_) => part = Part::bytes(bytes).file_name(filename),
    }
}
form = form.part(key, part);

(To be clear: this code compiles, but I did not actually end up testing it. I found this disagreeable enough to scrap it entirely.)

All I want is something like:

form = form.part(key, Part::bytes(bytes).file_name(filename).set_mime_best_guess());

Where it assigns a mime type from the filename, only if it can find a valid one -- the reqwest code already uses mime_guess for mime anyway -- and if I should still do the guessing myself, then I would like the set_mime() fn to be pub, since it's already there anyway.

Relevant code sections:

  • https://github.com/seanmonstar/reqwest/blob/0720159f6369f54e045a1fd315e0f24b7a0b4a39/src/blocking/multipart.rs#L45
  • https://github.com/seanmonstar/reqwest/blob/0720159f6369f54e045a1fd315e0f24b7a0b4a39/src/blocking/multipart.rs#L224
  • https://github.com/seanmonstar/reqwest/blob/0720159f6369f54e045a1fd315e0f24b7a0b4a39/src/blocking/multipart.rs#L248

I'm happy to put up a PR implementing my idea, if given the blessing to do so. And, certainly, if there is a better recommended approach, I will gladly use that. Thank you!

rogusdev avatar Apr 11 '24 02:04 rogusdev