4

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

1
  • Whats your Vue code? Commented May 20, 2017 at 19:30

3 Answers 3

11

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Following code works when selecting 1 file at a time. HTML code to show input field and a label using bootstrap classes:

<input type="file" class="custom-file-input" id="idEditUploadVideo"
       v-on:change="videoChoosen">
<label class="custom-file-label" id="idFileName" for="idEditUploadVideo">
    [[videoFileName]]</label>

JS code to show file name in the label as soon as user selects a file:

var vueVar = new Vue({
    el: '#idSomething',
    data: {
        videoFileName:''
    },
    methods: {
        videoChoosen(event){
            this.videoFileName = event.target.files[0].name;
        }
    },
    delimiters: ["[[", "]]"],
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.