oss_api/api/
oss_file_api.rs

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