rust tonic upload file

rust grpc upload file

依赖

1
2
3
4
5
6
7
8
9
10
11
12
[package]
name = "grpc"
version = "0.1.0"
edition = "2021"

[dependencies]
tonic = "0.7"
prost = "0.10"
tokio = { version = "1", features = ["full"] }

[build-dependencies]
tonic-build = "0.7"

编写 proto 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
syntax = "proto3";
package helloworld;


//服务定义
service Greeter{
//SayHello 是一个简单的 PRC 方法
rpc SayHello (HelloRequest) returns (HelloReply);

//客户端上传文件
rpc UploadFile (FileRequest) returns (FileResponse);

//客户端下载文件
rpc DownloadFile (DownloadRequest) returns (DownloadResponse);
}

//SayHello Request
message HelloRequest{
string name = 1;
}

//SayHello Reply
message HelloReply{
string message = 1;
}

//upload file Request
message FileRequest {
string file_name = 1; //文件名
bytes file_content = 2; //文件
}

//upload file Response
message FileResponse {
string message = 1;
}

//download file request
message DownloadRequest {
string file_name = 1;
}

//download file response
message DownloadResponse {
string file_name = 1;
bytes file_content = 2;
}

service.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104

use helloworld::greeter_server::{Greeter, GreeterServer};
use helloworld::{HelloReply,HelloRequest};



use tonic::{transport::Server, Request, Response, Status};
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

pub mod helloworld {
tonic::include_proto!("helloworld");
}

#[derive(Default)]
pub struct MyGreeter {}

#[tonic::async_trait]
impl Greeter for MyGreeter {
//打招呼
async fn say_hello(
&self,
request: Request<HelloRequest>,
) -> Result<Response<HelloReply>, Status> {
let name = request.into_inner().name;

println!("client name: {}",name);
let reply = HelloReply {
message: format!("Hello {}!", name),
};
Ok(Response::new(reply))
}

//上传文件
async fn upload_file(
&self,
request: Request<helloworld::FileRequest>,
) -> Result<Response<helloworld::FileResponse>, Status> {
let file_request = request.into_inner();

let file_name = file_request.file_name;
let file_content = file_request.file_content;

let mut file = File::create(file_name).await.map_err(|e| {
Status::internal(format!("Failed to create file: {}", e))
})?;

file.write_all(&file_content).await.map_err(|e| {
Status::internal(format!("Failed to write file: {}", e))
})?;

let reply = helloworld::FileResponse {
message: "File uploaded successfully".to_string(),
};

Ok(Response::new(reply))
}

//下载文件
async fn download_file(
&self,
request: Request<helloworld::DownloadRequest>,
) -> Result<Response<helloworld::DownloadResponse>, Status> {
let file_name = &request.into_inner().file_name;

// 打开文件并读取内容
let mut file = match File::open(file_name).await {
Ok(file) => file,
Err(e) => {
return Err(Status::not_found(format!("File not found: {}", e)));
}
};

let mut file_content = Vec::new();

match file.read_to_end(&mut file_content).await {
Ok(_) => (),
Err(e) => return Err(Status::internal(format!("Failed to read file: {}", e))),
};

let reply = helloworld::DownloadResponse {
file_name: file_name.to_string(),
file_content,
};

Ok(Response::new(reply))
}

}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = "[::1]:50051".parse()?;
let greeter = MyGreeter::default();

println!("Greeter server listening on {}", addr);

Server::builder()
.add_service(GreeterServer::new(greeter))
.serve(addr)
.await?;
Ok(())
}

client.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use std::time::Duration;

use helloworld::{greeter_client::GreeterClient, DownloadRequest, HelloRequest};
use tokio::io::AsyncWriteExt;


pub mod helloworld {
tonic::include_proto!("helloworld");
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
//let mut client = GreeterClient::connect("http://[::1]:50051").await?;

// 设置超时时间为 5 秒
let timeout = Duration::new(30, 0);

// 创建连接,设置超时
let channel = tonic::transport::Channel::from_static("http://[::1]:50051")
.timeout(timeout) // 设置超时
.connect()
.await?;
let mut client = GreeterClient::new(channel);
let request = tonic::Request::new(HelloRequest {
name: "东亚".into(),
});

let response = client.say_hello(request).await;

match response {
Ok(resp) => {
println!("Received: {:?}", resp.into_inner());
}
Err(e) => {
println!("Error occurred: {:?}", e);
}
}



//上传文件
let file_name = "guava-32.0.1-jre.jar";
let file_content = tokio::fs::read("E:\\devtools\\apache-maven-3.9.6\\lib\\guava-32.0.1-jre.jar").await?;

let request = tonic::Request::new(helloworld::FileRequest {
file_name: file_name.to_string(),
file_content,
});

let response = client.upload_file(request).await?;
println!("Response: {:?}", response.into_inner());


//下载文件
let file_name = "guava-32.0.1-jre.jar"; // 需要下载的文件名
// 请求下载文件
let request = tonic::Request::new(DownloadRequest {
file_name: file_name.to_string(),
});

let response = client.download_file(request).await?;

let download_response = response.into_inner();


// 保存下载的文件
// 拼接文件名,添加 "dwl" 前缀
let new_file_name = format!("dwl_{}", download_response.file_name);
// 保存下载的文件
let mut file = tokio::fs::File::create(new_file_name.clone()).await?;
file.write_all(&download_response.file_content).await?;

println!("File downloaded successfully: {}", new_file_name);


Ok(())
}

源代码

https://github.com/wchar-net/rust-grpc-demo