I need to send an array of images to an API using form-data, so I’m using a loop to add the images, but I’m getting an error.
fn main() {
let json = r#"{
"imgupload": ["/home/user/Pictures/image01.jpg", "/home/user/Pictures/image02.jpg"]
}"#
.to_string();
let request = serde_json::from_str::<ProductRequest>(json.as_str()).unwrap();
let mut form = reqwest::blocking::multipart::Form::new();
let array = request.imgupload.unwrap();
for file_path in array.iter() {
let file_name = get_file_name(file_path);
let part = get_request_part_from_file(&file_path, &file_name);
form.part("imgupload[]", part);
}
}
fn get_file_name(x: &String) -> String {
let file_name = std::path::Path::new(x)
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string();
file_name
}
fn get_request_part_from_file(
file_path: &String,
file_name: &String,
) -> reqwest::blocking::multipart::Part {
println!("{}", file_path);
let part = reqwest::blocking::multipart::Part::file(file_path)
.unwrap()
.file_name(file_name.to_string());
part
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ProductRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub imgupload: Option<Vec<String>>,
}
But I get the following error in form.part("imgupload[]", part); when trying to add reqwest::blocking::multipart::Part
What is the correct way to resolve this?
>Solution :
The part
method on reqwest::blocking::multipart::Form
takes ownership of self
and returns a new Form
with the part added.
Since it takes ownership of self
you can not re-use the form
variable after calling .part
on it.
To fix your code you can re-assign form
to the new Form
taht .part
returns:
fn main() {
let json = r#"{
"imgupload": ["/home/user/Pictures/image01.jpg", "/home/user/Pictures/image02.jpg"]
}"#
.to_string();
let request = serde_json::from_str::<ProductRequest>(json.as_str()).unwrap();
let mut form = reqwest::blocking::multipart::Form::new();
let array = request.imgupload.unwrap();
for file_path in array.iter() {
let file_name = get_file_name(file_path);
let part = get_request_part_from_file(&file_path, &file_name);
form = form.part("imgupload[]", part);
}
}