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;
6use std::sync::OnceLock;
7
8/// API
9pub static OSS_FILE_API: OnceLock<OssFileApi> = OnceLock::new();
10
11/// OSS FILE API
12#[derive(Debug)]
13pub struct OssFileApi {
14    pub api_settings: ApiSettings,
15}
16
17impl BaseApi for OssFileApi {
18    fn get_api_settings(&self) -> &ApiSettings {
19        &self.api_settings
20    }
21}
22
23impl OssFileApi {
24    /// 上传文件到指定的存储桶
25    ///
26    /// # Arguments
27    ///
28    /// * `bucket` - 存储桶名称
29    /// * `file_path` - 要上传的本地文件路径
30    /// * `file_name` - 上传后的文件名
31    ///
32    /// # Returns
33    ///
34    /// 返回上传结果
35    pub async fn upload_file(
36        &self,
37        bucket: &str,
38        file_path: &str,
39        file_name: &str,
40    ) -> Result<Ro<serde_json::Value>, Box<dyn std::error::Error>> {
41        let url = format!("/oss/file/upload/{}", bucket);
42        let form = reqwest::multipart::Form::new()
43            .file("file", file_path)
44            .await?
45            .text("fileName", file_name.to_string());
46
47        self.multipart(&url, form).await
48    }
49
50    /// 下载文件
51    ///
52    /// # Arguments
53    ///
54    /// * `obj_id` - 对象ID
55    ///
56    /// # Returns
57    ///
58    /// 返回下载的文件内容
59    pub async fn download_file(
60        &self,
61        obj_id: impl Display,
62    ) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
63        let url = format!("/oss/file/download/{}", obj_id);
64        self.get_bytes(&url).await
65    }
66
67    /// 预览文件
68    ///
69    /// # Arguments
70    ///
71    /// * `obj_id` - 对象ID
72    ///
73    /// # Returns
74    ///
75    /// 返回预览的文件内容
76    pub async fn preview_file(
77        &self,
78        obj_id: impl Display,
79    ) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
80        let url = format!("/oss/file/preview/{}", obj_id);
81        self.get_bytes(&url).await
82    }
83}