How to upload a file using rust or some library

How to upload a file using rust or some library in rust

But I need a working example, I've spend a day fighting compiler and rewrote the internet examples about 500 times. Finally managed to do a POST.

Next wanted to upload a file, don't want to waste a second day what takes few lines in other languages

This is what I have and now

let file = fs::File::open(filename);
let url = format!("{}bulk/script/upload/", baseURL);
let client = Client::new();
let response = client
	.post(&url)
	.header(reqwest::header::CONTENT_TYPE, "application/json")
	.header("developerKey", developerkey)
	.header("token", token)
	.body(file)
	.send()
	.await?;

now it complains about

.body(&file)
| ^^^^ the trait std::convert::From<&std::result::Result<std::fs::File, std::io::Error>> is not implemented for reqwest::async_impl::body::Body

What does it want this time

File::open can fail, so it returns a Result. There are a variety of ways to handle failures. One of the simplest is unwrap, which will panic on failure:

let file = fs::File::open(filename).unwrap();
1 Like

Note that you can avoid async/await using the reqwest::blocking module.

use std::fs;
use reqwest::blocking::Client;

let file = fs::File::open(filename).unwrap();
let url = format!("{}bulk/script/upload/", baseURL);
let client = Client::new();
let response = client
	.post(&url)
	.header(reqwest::header::CONTENT_TYPE, "application/json")
	.header("developerKey", developer_key)
	.header("token", token)
	.body(file)
	.send()
	.unwrap();

let text = response.text().unwrap(); // or whatever format you need

Or you can use the question mark where I have used .unwrap() above.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.