[英]Reset array for file upload
The attachments keeps getting the previous file selected.附件不断选择上一个文件。 If i selected 3 files, and then re-select again 2 files, the total files becomes 5 not 2. The attachments keeps adding up the files before and not reset when i want to re-select.如果我选择了 3 个文件,然后再次重新选择 2 个文件,则文件总数变为 5 个而不是 2 个。附件不断添加之前的文件,并且在我想重新选择时不会重置。 Thanks in advance.提前致谢。
Template模板
<input id="upload-file" type="file" multiple class="form-control" @change="fieldChange">
Script脚本
<script>
export default {
data(){
return{
year:'',
attachments:[],
form: new FormData
}
},
methods:{
fieldChange(e){
let selectedFiles=e.target.files;
if(!selectedFiles.length){
return false;
}
for(let i=0;i<selectedFiles.length;i++){
this.attachments.push(selectedFiles[i]);
}
console.log(this.attachments);
},
}
</script>
EDIT编辑
Also facing issues is that after submitting the form.同样面临的问题是提交表单后。 The form.pics[] still has the previous files and when submit the previous files will be saved again in the database. form.pics[] 仍然有以前的文件,提交时以前的文件将再次保存在数据库中。 I tried to reset it with form.pics = [] but doesn't work.我试图用 form.pics = [] 重置它但不起作用。
Script脚本
uploadFile(){
for(let i=0; i<this.attachments.length;i++){
this.form.append('pics[]',this.attachments[i]);
}
this.form.append('year',this.year);
axios.post('/api/gallery',this.form).then(response=>{
console.log(response);
this.form.pics = [];
})
.catch(response=>{
//error
});
}
Because you are pushing to the attachments and did not reset it.因为您正在推送附件并且没有重置它。
Try this尝试这个
<script>
export default {
data(){
return{
year:'',
attachments:[],
form: new FormData
}
},
methods:{
fieldChange(e){
this.attachments = []; // added this one
let selectedFiles=e.target.files;
if(!selectedFiles.length){
return false;
}
for(let i=0;i<selectedFiles.length;i++){
this.attachments.push(selectedFiles[i]);
}
console.log(this.attachments);
},
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.