wx_rust_common/util/fs/
file_utils.rs1pub struct FileUtils;
7
8impl FileUtils {
9 pub fn create_tmp_file(
20 content: &[u8],
21 name: &str,
22 ext: &str,
23 tmp_dir: Option<&std::path::Path>,
24 ) -> Result<std::path::PathBuf, std::io::Error> {
25 let dir = match tmp_dir {
26 Some(d) => d.to_path_buf(),
27 None => {
28 let base = std::env::temp_dir();
29 let d = base.join("wxjava-temp");
30 std::fs::create_dir_all(&d)?;
31 d
32 }
33 };
34 let mut path = dir.join(format!("{name}{}", std::process::id()));
36 let rand_suffix: String = (0..8)
38 .map(|_| {
39 let c = rand::random::<u8>() % 36;
40 if c < 10 {
41 (b'0' + c) as char
42 } else {
43 (b'a' + c - 10) as char
44 }
45 })
46 .collect();
47 path.set_file_name(format!("{name}{rand_suffix}.{ext}"));
48 std::fs::write(&path, content)?;
49 Ok(path)
51 }
52
53 pub fn image_to_base64_by_stream<R: std::io::Read>(
59 reader: &mut R,
60 ) -> Result<String, std::io::Error> {
61 use base64::Engine;
62 let mut data = Vec::new();
63 reader.read_to_end(&mut data)?;
64 Ok(base64::engine::general_purpose::STANDARD.encode(&data))
65 }
66}