Skip to main content

oss_api_client/api_client/
oss_file_api_client.rs

1use anyhow::anyhow;
2use reqwest::header::{HeaderMap, HeaderValue};
3use robotech::api_client::{ApiClient, ApiClientError};
4use robotech::cst::user_id_cst::USER_ID_HEADER_NAME;
5use robotech::ro::Ro;
6use std::fmt::Display;
7use std::ops::{Deref, DerefMut};
8use std::string::ToString;
9
10/// OSS FILE API
11#[derive(Debug)]
12pub struct OssFileApiClient {
13    pub api_client: ApiClient,
14}
15
16impl Deref for OssFileApiClient {
17    type Target = ApiClient;
18
19    fn deref(&self) -> &Self::Target {
20        &self.api_client
21    }
22}
23impl DerefMut for OssFileApiClient {
24    fn deref_mut(&mut self) -> &mut Self::Target {
25        &mut self.api_client
26    }
27}
28
29impl OssFileApiClient {
30    /// # 上传文件到指定的存储桶
31    ///
32    /// ## 参数
33    /// * `bucket` - 存储桶名称
34    /// * `file_path` - 要上传的本地文件路径
35    /// * `file_name` - 上传后的文件名
36    ///
37    /// ## 返回值
38    /// 返回上传结果
39    pub async fn upload_file(
40        &self,
41        bucket: &str,
42        file_path: &str,
43        file_name: &str,
44        current_user_id: u64,
45    ) -> Result<Ro<serde_json::Value>, ApiClientError> {
46        let url = format!("/oss/file/upload/{}", bucket);
47        let form = reqwest::multipart::Form::new()
48            .file("file", file_path)
49            .await
50            .map_err(|e| ApiClientError::ReadFile(url.clone(), e))?
51            .text("fileName", file_name.to_string());
52        let mut headers = HeaderMap::new();
53        headers.insert(
54            USER_ID_HEADER_NAME,
55            HeaderValue::from_str(&current_user_id.to_string().as_str())
56                .map_err(|e| anyhow!("current_user_id: {}", e))?,
57        );
58
59        self.multipart(&url, form, Some(headers), None).await
60    }
61
62    /// # 上传文件内容到指定的存储桶
63    ///
64    /// ## 参数
65    /// * `bucket` - 存储桶名称
66    /// * `file_path` - 要上传的本地文件路径
67    /// * `file_name` - 上传后的文件名
68    /// * `data` - 文件内容
69    ///
70    /// ## 返回值
71    /// 返回上传结果
72    pub async fn upload_file_content(
73        &self,
74        bucket: &str,
75        file_name: &str,
76        data: Vec<u8>,
77        current_user_id: u64,
78    ) -> Result<Ro<serde_json::Value>, ApiClientError> {
79        let url = format!("/oss/file/upload/{}", bucket);
80        let part = reqwest::multipart::Part::bytes(data).file_name(file_name.to_string());
81        let form = reqwest::multipart::Form::new().part("file", part);
82        let mut headers = HeaderMap::new();
83        headers.insert(
84            USER_ID_HEADER_NAME,
85            HeaderValue::from_str(&current_user_id.to_string().as_str())
86                .map_err(|e| anyhow!("current_user_id: {}", e))?,
87        );
88        self.multipart(&url, form, Some(headers), None).await
89    }
90
91    /// 下载文件
92    ///
93    /// # Arguments
94    ///
95    /// * `obj_id` - 对象ID
96    ///
97    /// # Returns
98    ///
99    /// 返回下载的文件内容
100    pub async fn download_file(
101        &self,
102        obj_id: impl Display,
103        current_user_id: u64,
104    ) -> Result<Vec<u8>, ApiClientError> {
105        let url = format!("/oss/file/download/{}", obj_id);
106        let mut headers = HeaderMap::new();
107        headers.insert(
108            USER_ID_HEADER_NAME,
109            HeaderValue::from_str(&current_user_id.to_string().as_str())
110                .map_err(|e| anyhow!("current_user_id: {}", e))?,
111        );
112        self.get_bytes::<()>(&url, None, Some(headers), None).await
113    }
114
115    /// # 预览文件
116    ///
117    /// ## Arguments
118    ///
119    /// * `obj_id` - 对象ID
120    ///
121    /// ## Returns
122    ///
123    /// 返回预览的文件内容
124    pub async fn preview_file(
125        &self,
126        obj_id: impl Display,
127        current_user_id: u64,
128    ) -> Result<Vec<u8>, ApiClientError> {
129        let url = format!("/oss/file/preview/{}", obj_id);
130        let mut headers = HeaderMap::new();
131        headers.insert(
132            USER_ID_HEADER_NAME,
133            HeaderValue::from_str(&current_user_id.to_string().as_str())
134                .map_err(|e| anyhow!("current_user_id: {}", e))?,
135        );
136        self.get_bytes::<()>(&url, None, Some(headers), None).await
137    }
138}