我正在使用vuejs和laravel尝试并能够上传多个文件但是在将输入中的文件数组分配给formData后,似乎没有任何反应。
HTML
<div id="app">
<form id="upload-form" enctype="multipart/form-data" v-if="isInitial() || isSaving()">
<div class="dropbox">
<input type="file" multiple id="upload-input" @change="uploadFile($event)" :disabled="isSaving()">
<p v-if="isInitial()">
Drag your file(s) here to begin<br> or click to browse
</p>
<p v-if="isSaving()" v-cloak>
Uploading (X amount of) files...
</p>
<p v-if="isSaved()" v-cloak>
Image Saved!
</p>
</div>
</form>
</div>
JAVASCRIPT
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: '#app',
data: {
Status: {
CurrentStatus: null,
Initial: 0,
Saving: 1,
Success: 2,
Saved: 3,
}
},
mounted(){
this.setInitial();
},
methods: {
setInitial(){
this.Status.CurrentStatus = this.Status.Initial;
},
uploadFile(event){
let formData = new FormData;
let length = event.target.files.count;
let files = event.target.files;
for(let x = 0; x < length; x++){
formData.append("files[]", files[x]);
}
console.log(formData);
this.CurrentStatus = this.Status.Saving;
axios.post('/upload/files', formData).then(x => {
console.log(x);
});
},
isInitial(){
return this.Status.CurrentStatus === this.Status.Initial;
},
isSaving(){
return this.Status.CurrentStatus === this.Status.Saving;
},
isSuccess(){
return this.Status.CurrentStatus === this.Status.Success;
},
isSaved(){
return this.Status.CurrentStatus === this.Status.Saved;
},
}
})
</script>
在我使用for循环i console.log设置formData之后的uploadFile方法中,它返回一个空的formData{}
对象。但是当我在console.log中调用files
变量时,它会返回我上传的所有图片的数组。
所以我认为错误是我的formdata对象以及如何设置它但我不确定,我从未搞砸过formdata而且我没有超级经验的JS。
我的问题
为什么formdata对象不是设置数据。
答案 0 :(得分:1)
尝试
let length = event.target.files.length
而不是......
let length = event.target.files.count
答案 1 :(得分:1)
我认为有几个问题。
let formData = new FormData;
应该是
let formData = new FormData();
,您需要指定标题
axios.post('/upload/files', formData, {
headers: {
'content-type': 'multipart/form-data'
}
}).then(x => {
console.log(x);
});
答案 2 :(得分:1)
您应该尝试
let formData = new FormData(event.target);
在功能上为:
uploadFile(event){
let formData = new FormData(event.target);
console.log(formData);
axios.post('/upload/files', formData).then(x => {
console.log(x);
});
}