oss_api/api/
oss_file_api.rs

1use robotech::api::api_settings::ApiSettings;
2use robotech::api::base_api::BaseApi;
3use robotech::ro::Ro;
4use std::fmt::Display;
5use std::string::ToString;
6
7/// OSS FILE API
8#[derive(Debug)]
9pub struct OssFileApi {
10    pub api_settings: ApiSettings,
11}
12
13impl BaseApi for OssFileApi {
14    fn get_api_settings(&self) -> &ApiSettings {
15        &self.api_settings
16    }
17}
18
19impl OssFileApi {
20    /// # 上传文件到指定的存储桶
21    ///
22    /// ## 参数
23    /// * `bucket` - 存储桶名称
24    /// * `file_path` - 要上传的本地文件路径
25    /// * `file_name` - 上传后的文件名
26    ///
27    /// ## 返回值
28    /// 返回上传结果
29    pub async fn upload_file(
30        &self,
31        bucket: &str,
32        file_path: &str,
33        file_name: &str,
34        current_user_id: u64,
35    ) -> Result<Ro<serde_json::Value>, Box<dyn std::error::Error + Send + Sync>> {
36        let url = format!("/oss/file/upload/{}", bucket);
37        let form = reqwest::multipart::Form::new()
38            .file("file", file_path)
39            .await?
40            .text("fileName", file_name.to_string());
41
42        self.multipart(&url, form, current_user_id).await
43    }
44
45    /// # 上传文件内容到指定的存储桶
46    ///
47    /// ## 参数
48    /// * `bucket` - 存储桶名称
49    /// * `file_path` - 要上传的本地文件路径
50    /// * `file_name` - 上传后的文件名
51    /// * `data` - 文件内容
52    ///
53    /// ## 返回值
54    /// 返回上传结果
55    pub async fn upload_file_content(
56        &self,
57        bucket: &str,
58        file_name: &str,
59        data: Vec<u8>,
60        current_user_id: u64,
61    ) -> Result<Ro<serde_json::Value>, Box<dyn std::error::Error + Send + Sync>> {
62        let url = format!("/oss/file/upload/{}", bucket);
63        let part = reqwest::multipart::Part::bytes(data).file_name(file_name.to_string());
64        let form = reqwest::multipart::Form::new().part("file", part);
65        self.multipart(&url, form, current_user_id).await
66    }
67
68    /// 下载文件
69    ///
70    /// # Arguments
71    ///
72    /// * `obj_id` - 对象ID
73    ///
74    /// # Returns
75    ///
76    /// 返回下载的文件内容
77    pub async fn download_file(
78        &self,
79        obj_id: impl Display,
80        current_user_id: u64,
81    ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
82        let url = format!("/oss/file/download/{}", obj_id);
83        self.get_bytes(&url, current_user_id).await
84    }
85
86    /// # 预览文件
87    ///
88    /// ## Arguments
89    ///
90    /// * `obj_id` - 对象ID
91    ///
92    /// ## Returns
93    ///
94    /// 返回预览的文件内容
95    pub async fn preview_file(
96        &self,
97        obj_id: impl Display,
98        current_user_id: u64,
99    ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
100        let url = format!("/oss/file/preview/{}", obj_id);
101        self.get_bytes(&url, current_user_id).await
102    }
103}