make a http request with a custom body as multipart form data in rust

You can make an HTTP request with a custom body as multipart form data in Rust by utilizing a library called reqwest.

To use this library, you can add the following line to your Cargo.toml file:

[dependencies]
reqwest = { version = "0.11.1", features = ["multipart"] }
74 chars
3 lines

And then you can use the following code to make a POST request with a multipart form data body:

main.rs
use std::fs::File;
use std::io::prelude::*;

use reqwest::blocking::Client;
use reqwest::multipart::{Form, Part};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    let mut file = File::open("path/to/file.ext")?;
    let mut body = Vec::new();
    file.read_to_end(&mut body)?;

    let form = Form::new()
        .part(
            "field_name",
            Part::bytes(body)
                .file_name("file.ext")
                .mime_type("application/octet-stream"),
        );

    let response = client
        .post("https://example.com/upload")
        .multipart(form)
        .send()?;
    println!("{:?}", response);
    Ok(())
}
682 chars
28 lines

In this code, you first create a Client instance from the reqwest::blocking module. You then read the contents of your file into a byte vector.

Next, you create a Form instance by using the Form::new() method, and add the file contents as one of the parts of the form. The Part::bytes() method is used to create a Part instance from the reqwest::multipart module containing the byte vector, and file_name and mime_type are used to set the name and mime-type of the file to be uploaded.

Finally, you make a POST request to your desired URL by chaining .post() to your client, passing in the URL to post to, and then chaining .multipart() to this with the Form instance as its argument. You can then call send() on the request object to execute it, and inspect the returned response object as desired.

gistlibby LogSnag