Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuetify File Uploads

I'm trying to upload a file in Vue.js using vuetify and then save the uploaded file in my data object.

HTML:

<input id="file-upload" type="file" @change="onFileChange">

In my methods I call:

onFileChange(e) {

  var files = e.target.files || e.dataTransfer.files;
  if (!files.length) {
    return;
  }   
  this.editedPerson.id_file = e.target.files[0].name;
},

This works 100%.

I do, however, want to use the Vuetify component:

<v-btn color="blue-grey" class="white--text" @click.native="openFileDialog">Upload<v-icon right dark>cloud_upload</v-icon></v-btn>

I hide the original file input tag but on this v-btn component I call the following method:

openFileDialog() {
  document.getElementById('file-upload').click();
},

So when I click on the v-btn component it simulates a click on the hidden file input tag and I can choose a file.

On change of the input tag I can still console.log the uploaded file but

this.editedPerson.id_file = e.target.files[0].name;

no longer works.

Is there any reason why this happens?

like image 642
Marcus Christiansen Avatar asked Sep 18 '26 06:09

Marcus Christiansen


1 Answers

This following code works fine for me. I've used axois for HTTPClient you might choose anything

<div id="app">
   <v-btn color="blue-grey" class="black--text" @click.native="openFileDialog">
    Upload
    <v-icon right dark> cloud_upload</v-icon>
   </v-btn>
   <input type="file" id="file-upload" style="display:none" @change="onFileChange">
</div> 


Vue.use(Vuetify);
var vm = new Vue({
    el: "#app",
    data: {
        formData: new FormData(),
    },
    methods: {
        openFileDialog() {
            document.getElementById('file-upload').click();
        },
        onFileChange(e) {
            var self = this;
            var files = e.target.files || e.dataTransfer.files;       
            if(files.length > 0){
                for(var i = 0; i< files.length; i++){
                    self.formData.append("file", files[i], files[i].name);
                }
            }   
        },
        uploadFile() {
            var self = this; 
            axios.post('URL', self.formData).then(function (response) {
                console.log(response);
            }).catch(function (error) {
                console.log(error);
            });
        },
    },

});
like image 193
Monirul Islam Avatar answered Sep 19 '26 21:09

Monirul Islam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!