Reputation: 1326
Following scenarion:
User fills out form which includes v-file-input
. The files attached are also sent to server and saved there. User has option to edit
the form. All the fields of the form are filled with the saved data. How can I fill the v-file-input
field with dynamically with the saved files?
Upvotes: 0
Views: 1996
Reputation: 2411
So your server will need to base64 convert your files for this solution. Note: Client = the Vue application.
Client requests file data in base64 format from the server (RESTful Endpoint or other means, your choice). This should be done in a created
hook, and assigned to a data property (I'll use myFileBase64
as an example).
Client has a computed property myFileAsFile
that calls the below function (credit) to convert myFileBase64
from base64 to type File
:
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
//Usage example:
var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');
console.log(file);
v-input
to myFileAsFile
. This can be done via v-bind:value
Here is a Codepen demonstrating the assignment part of my answer: https://codepen.io/Qumez/pen/OJVxvYY
Upvotes: 1