Vuetify文件上传 [英] Vuetify File Uploads
问题描述
我正在尝试使用vuetify在Vue.js中上传文件,然后将上传的文件保存在我的数据对象中.
I'm trying to upload a file in Vue.js using vuetify and then save the uploaded file in my data object.
HTML:
<input id="file-upload" type="file" @change="onFileChange">
在我的方法中,我调用:
In my methods I call:
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length) {
return;
}
this.editedPerson.id_file = e.target.files[0].name;
},
这有效100%.
但是,我确实想使用Vuetify组件:
I do, however, want to use the Vuetify component:
<v-btn color="blue-grey" class="white--text" @click.native="openFileDialog">Upload<v-icon right dark>cloud_upload</v-icon></v-btn>
我隐藏了原始文件输入标签,但是在此v-btn组件上,我调用了以下方法:
I hide the original file input tag but on this v-btn component I call the following method:
openFileDialog() {
document.getElementById('file-upload').click();
},
因此,当我单击v-btn组件时,它模拟了对隐藏文件输入标签的单击,因此我可以选择一个文件.
So when I click on the v-btn component it simulates a click on the hidden file input tag and I can choose a file.
更改输入标签后,我仍然可以console.log上载的文件,但是
On change of the input tag I can still console.log the uploaded file but
this.editedPerson.id_file = e.target.files[0].name;
不再有效.
有什么原因会发生这种情况吗?
Is there any reason why this happens?
推荐答案
以下代码对我来说很好.我已经将axois用于HTTPClient,您可能会选择
This following code works fine for me. I've used axois for HTTPClient you might choose anything
<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);
});
},
},
});
这篇关于Vuetify文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!