Mar*_*sen 3 html file-upload vue.js vuetify.js
我正在尝试使用 vuetify 在 Vue.js 中上传文件,然后将上传的文件保存在我的数据对象中。
HTML:
<input id="file-upload" type="file" @change="onFileChange">
Run Code Online (Sandbox Code Playgroud)
在我的方法中,我调用:
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length) {
return;
}
this.editedPerson.id_file = e.target.files[0].name;
},
Run Code Online (Sandbox Code Playgroud)
这 100% 有效。
但是,我确实想使用 Vuetify 组件:
<v-btn color="blue-grey" class="white--text" @click.native="openFileDialog">Upload<v-icon right dark>cloud_upload</v-icon></v-btn>
Run Code Online (Sandbox Code Playgroud)
我隐藏了原始文件输入标签,但在这个 v-btn 组件上,我调用了以下方法:
openFileDialog() {
document.getElementById('file-upload').click();
},
Run Code Online (Sandbox Code Playgroud)
所以当我点击 v-btn 组件时,它模拟点击隐藏文件输入标签,我可以选择一个文件。
在更改输入标签时,我仍然可以使用 console.log 上传文件,但是
this.editedPerson.id_file = e.target.files[0].name;
Run Code Online (Sandbox Code Playgroud)
不再有效。
发生这种情况有什么原因吗?
小智 5
以下代码对我来说很好用。我已经将 axois 用于 HTTPClient 你可以选择任何东西
<div id="app">
<v-btn color="blue-grey" class="black--text" @click.native="openFileDialog">
Upload
<v-icon right dark> cloud_upload</v-icon>
</v-btn>
<input type="file" id="file-upload" style="display:none" @change="onFileChange">
</div>
Vue.use(Vuetify);
var vm = new Vue({
el: "#app",
data: {
formData: new FormData(),
},
methods: {
openFileDialog() {
document.getElementById('file-upload').click();
},
onFileChange(e) {
var self = this;
var files = e.target.files || e.dataTransfer.files;
if(files.length > 0){
for(var i = 0; i< files.length; i++){
self.formData.append("file", files[i], files[i].name);
}
}
},
uploadFile() {
var self = this;
axios.post('URL', self.formData).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
},
},
});
Run Code Online (Sandbox Code Playgroud)