VueJS3 + Typescript - Read file from input file

Viewed 703

I want to upload some file, but I can't access with v-model

VueCompilerError: v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.

So, I've change the v-model to v-on:change like code below, but I don't know how to do this

<input
  type="file"
  name="file"
  v-on:change="uploadFile"
  style="display: none; border: none"
/>

I read a big list of examples, but none worked.

My data (Idk if it's right):

data() {
  return {
    file: null as unknown as File,
  };
},
2 Answers

A basic example could look like this

<input type="file" @change="onFileChange">

JavaScript version

methods: {
  onFileChange(e) {
    let files = e.target.files || e.dataTransfer.files;
    if (!files.length) 
      return;

    doSomethingWithTheFile(files[0]);
  },
}

TypeScript version could look like this

interface HTMLInputEvent extends Event {
  target: HTMLInputElement & EventTarget
}


methods: {
  onFileChange(event: HTMLInputEvent | DragEvent) {
    let files =
      (event as HTMLInputEvent).target.files ||
      (event as DragEvent).dataTransfer.files
    if (!files.length) return

    doSomethingWithTheFile(files[0])
  },
},

What does your uploadFile look like?

The simpler may be to declare it to take directly the files list:

async uploadFiles(fileList: Array<File>) {
    for (const file of fileList) {
        // do something with the file

And call it this way:

v-on:change="uploadFiles($event.target.files)"
Related