【问题标题】:Reset array for file upload文件上传重置数组
【发布时间】:2023-04-07 09:35:01
【问题描述】:

附件不断选择上一个文件。如果我选择了 3 个文件,然后再次重新选择 2 个文件,则文件总数变为 5 个而不是 2 个。附件不断添加之前的文件,并且在我想重新选择时不会重置。提前致谢。

模板

<input id="upload-file" type="file" multiple class="form-control" @change="fieldChange">

脚本

<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>

编辑

同样面临的问题是提交表单后。 form.pics[] 仍然有以前的文件,提交时以前的文件将再次保存在数据库中。我尝试使用 form.pics = [] 重置它,但不起作用。

脚本

 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
            });
        }

【问题讨论】:

    标签: javascript php laravel vue.js


    【解决方案1】:

    因为您正在推送到附件并且没有重置它。

    试试这个

    <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>
    

    【讨论】:

    • 完美运行,介意看看我的新问题。我编辑了帖子。谢谢
    • this.form.pics 不起作用,因为 this.form 不是对象。建议不要在数据中声明new FormData。尝试在fieldChange 方法中声明const form = new FormData
    • @HelloWorld1014 如果这个答案有助于记住接受这个作为解决方案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-03-31
    • 1970-01-01
    • 2013-02-09
    • 2013-10-02
    • 2016-10-23
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多