Skip to main content

wx_rust_common/bean/
common_upload_data.rs

1//! 通用文件上传数据。
2//!
3//! 对应 Java `me.chanjar.weixin.common.bean.CommonUploadData`。
4
5/// 通用文件上传数据。
6///
7/// 承载上传文件的文件名、内容与长度;内容以字节切片形式持有
8/// (对应 Java `InputStream`,Rust 侧由调用方提供 `Vec<u8>`)。
9#[derive(Debug, Clone)]
10pub struct CommonUploadData {
11    /// 文件名,如 `1.jpg`
12    pub file_name: Option<String>,
13
14    /// 文件内容
15    pub content: Vec<u8>,
16
17    /// 文件内容长度(字节数)
18    pub length: u64,
19}
20
21impl CommonUploadData {
22    /// 从字节内容构建上传数据。
23    ///
24    /// # 参数
25    /// - `file_name`:文件名(可为 `None`)
26    /// - `content`:文件内容字节
27    pub fn new(file_name: Option<String>, content: Vec<u8>) -> Self {
28        let length = content.len() as u64;
29        Self {
30            file_name,
31            content,
32            length,
33        }
34    }
35
36    /// 从文件路径构建上传数据(读取整个文件到内存)。
37    ///
38    /// # 参数
39    /// - `file`:文件路径
40    ///
41    /// # 返回
42    /// 上传数据;读取失败时返回错误。
43    pub fn from_file(file: &std::path::Path) -> Result<Self, std::io::Error> {
44        let content = std::fs::read(file)?;
45        let file_name = file.file_name().map(|n| n.to_string_lossy().into_owned());
46        Ok(Self::new(file_name, content))
47    }
48}