7

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
  • 23,478
  • 6
  • 59
  • 81
Pixel Coder
  • 139
  • 1
  • 1
  • 6

2 Answers2

12

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 mut file = fs::OpenOptions::new()
    // .create(true) // To create a new file
    .write(true)
    // either use the ? operator or unwrap since it returns a Result
    .open("/path/to/file")?;

file.write_all(&file_contents_base64);
Anthony
  • 2,014
  • 2
  • 19
  • 29
Aplet123
  • 33,825
  • 1
  • 29
  • 55
7

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
  • 23,478
  • 6
  • 59
  • 81