0

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?

farahm
  • 1,326
  • 6
  • 32
  • 70

1 Answers1

1

So your server will need to base64 convert your files for this solution. Note: Client = the Vue application.

  1. 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).

  2. 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);
  1. Client sets the value of the 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

Tanner
  • 2,232
  • 13
  • 22