在 vue.js 中更改的文件输入

使用普通的 HTML/JS,可以查看所选文件的 JavaScript File 对象的输入元素,如下所示:

<input type="file" id="input" multiple onchange="handleFiles(this.files)">

但是,当将它转换为“ Vue”方式时,它似乎不能按预期的方式工作,只是返回 undefined,而不是返回一个 File 对象的 Array。

这是它在我的 Vue 模板中的样子:

<input type="file" id="file" class="custom-file-input"
v-on:change="previewFiles(this.files)" multiple>

其中 previewFiles函数简单如下(位于方法中) :

  methods: {
previewFiles: function(files) {
console.log(files)
}
}

有没有替代或者正确的方法? 谢谢

162689 次浏览

Try this.

<input type="file" id="file" ref="myFiles" class="custom-file-input"
@change="previewFiles" multiple>

and in your component options:

data() {
return {
files: [],
}
},
methods: {
previewFiles() {
this.files = this.$refs.myFiles.files
}
}

Another solution:

<input type="file" @change="previewFiles" multiple>


methods: {
previewFiles(event) {
console.log(event.target.files);
}
}
<form ref="form">
<input type="file" @change="previewFiles" multiple tabindex="-1">
</form>


methods: {
previewFiles(event) {


// process your files, read as DataUrl or upload...
console.log(event.target.files);


// if you need to re-use field or drop the same files multiple times
this.$refs.form.reset()


}
}

On Safari, you might face an issue when @input/change event won't fire.

tabindex="-1" - it's a magic trick to make it works on Safari (13.0.2)

For all the TS-Users out there:

<template>
<input ref="upload"
type="file"
name="file-upload"
multiple=""
accept="image/jpeg, image/png"
@change="onUploadFiles">
</template>
import { Component, Prop, Vue } from 'vue-property-decorator';


@Component({ components: {} })
export default class MediaEdit extends Vue {


private onUploadFiles(event: InputEvent): void {
const files: ReadonlyArray<File> = [...(this.upload.files ? this.upload.files : [])];


files.forEach((file) => {
console.log(`File: ${file.name}`);
});
}


/** Upload element */
private get upload(): HTMLInputElement {
return this.$refs.upload as HTMLInputElement;
}
}