Rust Reqwest multipart上传文件示例

Rust Reqwest multipart上传文件示例

客户端示例代码

示例包含了asyncblocking两种,根据自身需要合理修改依赖项

依赖项 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随意

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值