Reputation: 305
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?
Upvotes: 3
Views: 6871
Reputation: 3285
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;
}
Upvotes: 8
Reputation: 171
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)
Upvotes: -1