3

i have a component like this

<input type="file" multiple @change="toBase64Handler($event)">

<script>
 data() {
  return {
     files: [],
   }
 },
 methods: {
  tobase64Handler(event) {
   // the code
  }
 }
</script>

and i would like to turn all of the selected files into base64 string something like this:

files: [
  {
   selectedFile: 'ajsdgfauywdljasvdajsgvdasdo1u2ydfouayvsdlj2vo8ayasd...'
  },
  {
   selectedFile: 'askdhgoiydvywdljasvdajsgvdasdo1u2ydfoakjgsfdjagswsd...'
  },
  {
   selectedFile: '12edashjvlsljasvdajsgvdasdo1u2ydfouayvsdlj2vo8ayfsd...'
  },
]

how do i achieve that?

dunhilblack
  • 195
  • 1
  • 4
  • 13
  • Possible duplicate of [How to convert file to base64 in JavaScript?](https://stackoverflow.com/questions/36280818/how-to-convert-file-to-base64-in-javascript) – Fab Nov 20 '19 at 15:02
  • i cant seem to access the index of the FileList :/ – dunhilblack Nov 20 '19 at 15:09

2 Answers2

7

You can loop though the files call a helper method toBase64, push all Promises to an array and resolve all of them:

  toBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  };

  async tobase64Handler(files) {
    const filePathsPromises = [];
    files.forEach(file => {
      filePathsPromises.push(this.toBase64(file));
    });
    const filePaths = await Promise.all(filePathsPromises);
    const mappedFiles = filePaths.map((base64File) => ({ selectedFile: base64File }));
    return mappedFiles;
  }
Simon Thiel
  • 2,888
  • 6
  • 24
  • 46
-1

this should do the trick: JSON.stringify(files) you can read more about it here. If you later want to turn it back into the original array, object, or value then you'd do JSON.parse(files). you can read more about it here

UPDATE: turns out I was wrong and JSON.stringify/parse don't work with files(thanks for the info @patrick evans). found this answer which seems better (the one by @ahmed hamdy)

person13
  • 141
  • 9
  • 1
    `JSON.stringify` does not transform File/Blob objects into base64 encoded strings of their contents. Nor conversely will `JSON.parse` parse a base64 string and turn it into a File/Blob – Patrick Evans Nov 20 '19 at 15:07