oss_api/api/
oss_file_api.rs

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