Parth Sahu
Parth Sahu

Reputation: 53

Vue - File input element's @change not triggered when its files are set using ref - drag and drop file upload

I have a file input for drag and drop image upload.

    <input
          type="file"
          ref="FileInput"
          style="display: none;"
          @change="onFileSelect"
          accept=".jpg,.jpeg,.png,.tiff,.webp"
        />

which triggers an OnFileSelect function on change.

onFileSelect(e) {
      console.log("came here");
      const file = e.target.files[0];
      ...
      ...
      // here the code sends the files to be uploaded in server
}

There is a dropzone which contains the input field:

<div
      ref="dropZone"
      @drop="onDrop($event)"
      @click="$refs.FileInput.click()"
    >

and the onDrop function is as follows:

onDrop(e) {
      this.$refs.FileInput.files = e.dataTransfer.files;
      //this changes fileList in input but the onChange in input field is not triggered
      console.log("Yes", this.$refs.FileInput.files);
    },

While onDrop is triggered when I drop an image file in dropzone and the Filelist in input is also changed, the function onFileSelect (which should trigger when input changes) is not being called after the onDrop function. How can I achieve this? Thanks in advance!

Upvotes: 3

Views: 3518

Answers (1)

Rahul
Rahul

Reputation: 5834

onChange event of input type files will not trigger on dropEnd.

Instead you have to modify your current onChange method. So that you use the same code for drop end.

Update your onFileSelect method like this:

onFileSelect(e) {
      console.log("came here");
      const file = e.target.files[0];

      uploadFile(file) // this method will be responsible for uploading file to server. Move all code written in onFileSelect to this method.
}

Now on DropEnd, simple call this method with file parameter.

onDrop(e) {
     uploadFile(e.dataTransfer.files[0])
    },

Upvotes: 3

Related Questions