Home > Software engineering >  How to add files from file input into array in Firefox browser?
How to add files from file input into array in Firefox browser?

Time:08-24

(I'm using vue 3) I'm adding files from input file to array, then I conditionally render these file names. All working good on Chrome. Problem is when using Mozilla Firefox. In this browser array of files is overrided by last added file, for example:

  1. add file-1 || output: file-1
  2. add file-1 and next file-2 || output: file-1 file-1 (duplication).

There you can view and test this code: https://codesandbox.io/s/elegant-poitras-exux2z?file=/src/App.vue
method:

methods: {
addFile (file) {
  this.form.files.push(file);
}}

data structure:

  data() {
    return {
      form: {
        files: [],
      }};},

output:

<div>
<input @input="addFile($event.target.files)" type="file" name="" id="">
<p  v-for="file in form.files" :key="file">
            {{ file[0].name }}
</p>
</div>

CodePudding user response:

Got a fix for you

methods: {
    addFile(file) {
        this.form.files.push({ ...file });
    }
}

Reason is - well, my theory is that $event.target.files is not a new object every time addFile($event.target.files) is called

You'll see this if you change your code to

methods: {
    addFile(file) {
        if (this.form.files.length) {
            console.log(this.form.files[0] === file)
        }
        this.form.files.push(file);
    }
}

This logs true in Firefox 103, but false in Firefox 104 (dev version)

Another alternative

<p v-for="file in form.files" :key="file">
  {{ file.name }}
</p>

methods: {
  addFile(file) {
    this.form.files.push(file[0]);
  },
}
  • Related