Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js show file name event.target.files

I'm making an upload functionality in my webapp with vue 2. Currently it looks like this:

<label class="btn btn-xs btn-primary">
    <input type="file" name="attachment[]" @change="onFileChange" multiple/>
    Upload file
</label>

input[type="file"]  {
  display: none;
}


onFileChange() {
    this.reaction.attachment = event.target.files || event.dataTransfer.files;
}

So now I would like to show the file names that are on the event.target.files object.

I've tried this:

<p v-for="file in reaction.attachment">
  {{ file.name }}
</p>

But that's not working!? When I look into my vue devtools the attachment object looks like this:

attachment:FileList

So how do I get this to work?

Thanks a lot

like image 978
Jamie Avatar asked Sep 11 '25 23:09

Jamie


2 Answers

You need to get file name using document.getElementById("fileId").files[0].name inside onFileChange function.

<label class="btn btn-xs btn-primary">
    <input type="file" name="attachment[]" id="fileId" @change="onFileChange" multiple/>
    Upload file
</label>
{{fileName}}


input[type="file"]  {
  height:0;
  weight:0;
  //OR
  display:none
}

Inside script, pass event to the function.

onFileChange(event){
   var fileData =  event.target.files[0];
   this.fileName=fileData.name;
}
like image 58
Helping hand Avatar answered Sep 14 '25 12:09

Helping hand


I have created a working example in the sandbox you can check it out. It will work either select one file or multiple https://codesandbox.io/s/condescending-wildflower-jljxn?file=/src/App.vue

like image 23
MOHD SHAHZAIB Avatar answered Sep 14 '25 12:09

MOHD SHAHZAIB