qiniu_upload_rs/upload/
data_uploader.rs1use crate::upload;
2use crate::utils::auth::Auth;
3use crate::utils::qiniu_err::{QiniuErr, QiniuErrCode};
4use crate::utils::verification::crc32;
5
6use reqwest::blocking::multipart::{Form, Part};
7use reqwest::blocking::Client;
8
9pub struct DataUploader {
10 auth: Auth,
11}
12
13impl DataUploader {
14 pub fn new(auth: Auth) -> Self {
15 Self { auth }
16 }
17
18 pub fn upload(
19 &self,
20 bucket: &str,
21 key: &str,
22 expired_seconds: u64,
23 data: &'static [u8],
24 ) -> Result<(), QiniuErr> {
25 let form = self.build_form(bucket, key, expired_seconds, data)?;
26 self.upload_form(form)
27 }
28
29 fn build_form(
30 &self,
31 bucket: &str,
32 key: &str,
33 expired_seconds: u64,
34 data: &'static [u8],
35 ) -> Result<Form, QiniuErr> {
36 let token = self.auth.upload_token(bucket, key, expired_seconds);
37 let crc = crc32(data);
38 let file_part = self.build_form_file_part(key, upload::UPLOAD_MIME_TYPE, data)?;
39
40 let form = Form::new()
41 .text("token", token)
42 .text("key", key.to_string())
43 .text("ctc32", crc.to_string())
44 .part("file", file_part);
45
46 Ok(form)
47 }
48
49 fn build_form_file_part(
50 &self,
51 filename: &str,
52 mime_type: &str,
53 data: &'static [u8],
54 ) -> Result<Part, QiniuErr> {
55 let result = Part::bytes(data)
56 .file_name(filename.to_string())
57 .mime_str(mime_type);
58 match result {
59 Ok(file_part) => Ok(file_part),
60 Err(err) => Err(QiniuErr {
61 message: err.to_string(),
62 code: QiniuErrCode::Inval,
63 }),
64 }
65 }
66
67 fn upload_form(&self, form: Form) -> Result<(), QiniuErr> {
68 let result = Client::new()
69 .post(upload::UPLOAD_URL)
70 .multipart(form)
71 .send();
72 if let Err(err) = result {
73 return Err(QiniuErr {
74 message: err.to_string(),
75 code: QiniuErrCode::Inval,
76 });
77 }
78
79 let status_code = result.unwrap().status();
80 if status_code.is_success() {
81 Ok(())
82 } else if status_code.is_server_error() {
83 let message = status_code.as_str().to_string();
84 Err(QiniuErr {
85 message,
86 code: QiniuErrCode::BadResponse,
87 })
88 } else {
89 Err(QiniuErr {
90 message: "".to_string(),
91 code: QiniuErrCode::Unknown,
92 })
93 }
94 }
95}