Rust Reqwest multipart上传文件示例
客户端示例代码
示例包含了async
和blocking
两种,根据自身需要合理修改依赖项
依赖项 Cargo.toml
[package]
edition = "2021"
name = "file-upload-client"
version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = { version = "*" }
reqwest = { version = "*", features = ["stream", "multipart", "blocking"] }
tokio = { version = "*", features = ["macros", "rt-multi-thread"] }
tokio-util = { version = "*", features = ["codec"] }
示例代码 main.rs
use anyhow::{Ok, Result};
use reqwest::{
multipart::{self, Part},
Body,
};
use tokio_util::codec::{BytesCodec, FramedRead};
#[tokio::main]
async fn main() {
let filename = upload().await.unwrap();
println!("{}", filename);
let filename = tokio::task::spawn_blocking(sync_upload)
.await
.unwrap()
.unwrap();
println!("{}", filename);
}
async fn upload() -> Result<String> {
let file = tokio::fs::File::open("Cargo.toml").await.unwrap();
let read = FramedRead::new(file, BytesCodec::new());
let body = Body::wrap_stream(read);
let form = multipart::Form::new()
.text("name", "value")
.part("file", Part::stream(body).file_name("Cargo.toml"));
let client = reqwest::Client::new();
Ok(client
.post("http://localhost:8080/upload")
.multipart(form)
.send()
.await?
.text()
.await?)
}
fn sync_upload() -> Result<String> {
let form = reqwest::blocking::multipart::Form::new()
.text("name", "value")
.file("file", "Cargo.lock")?;
let client = reqwest::blocking::Client::new();
Ok(client
.post("http://localhost:8080/upload")
.multipart(form)
.send()?
.text()?)
}
服务端示例代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@Slf4j
@RestController
public class FileController {
@RequestMapping("/upload")
public String upload(MultipartFile file) {
String name = file.getOriginalFilename();
log.info(name);
return name;
}
}
运行结果
参考地址
https://stackoverflow.com/questions/65814450/how-to-post-a-file-using-reqwest
注意
Part需要指定文件名称,mime随意