3

I have a base64 image and got Vec<u8> from it and write them to a file. Here is my code:

let file_contents_base64: Vec<u8> = image_base64::from_base64(
    String::from(&file_contents_string_vec[0])
);

I want to write the file_contents_base64 variable to a file.

vallentin
  • 21,302
  • 6
  • 52
  • 73
Pixel Coder
  • 79
  • 1
  • 4

2 Answers2

4

In addition to fs::write, there's a generalized solution for everything implementing the Write trait, by using write_all:

use std::io::Write; // bring trait into scope
use std::fs;

// ... later in code
let file = OpenOptions::new()
    .write(true)
    // either use ? or unwrap since it returns a Result
    .open("/path/to/file")?;

file.write_all(&file_contents_base64);
Aplet123
  • 30,962
  • 1
  • 21
  • 47
2

The fact that you're using the image-base64 crate seems less relevant to the question. Considering you just want to write a Vec<u8> to a file, then you can just use e.g. fs::write():

use std::fs;
use std::path::Path;

let file_contents_base64: Vec<u8> = ...;
let path: &Path = ...;

fs::write(path, file_contents_base64).unwrap();
vallentin
  • 21,302
  • 6
  • 52
  • 73