Vue-resource上传图片到服务器

首先,表单代码

<form  class="upload-form" v-show="show_upload_page" method="post"  enctype="multipart/form-data">
    <div >
        <input class="select-file" type="file" name="files" @change="bindFiles($event)" multiple/>
    </div>
    <div>
        <input class="category-txt" type="text" name="category" v-model="upload_category"  placeholder="请输入类别" />
    </div>
    <div>
        <input class="submit-btn" type="button" value="上传" v-on:click.prevent="upload()"/>
    </div>
</form>

javascript:

<script>
    new Vue({
        el: '#app',
        data:{
          upload_files:[],
          upload_category:''
        },
        methods:{
            bindFiles(event){
               //获取文件
                let files = event.target.files;
                //将文件push到upload_files
                for(let i = 0; i < files.length;i++){
                    this.upload_files.push(files[i]);
                }
            },
            upload(){
                let formData = new FormData();
                for (let i = 0;i < this.upload_files.length;i++){
                    formData.append('files',this.upload_files[i]);
                }
                formData.append('category',this.upload_category);

                this.$http.post(this.host + '/file',
                        formData,
                        {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        }).then(function (){
                            alert("文件上传成功");
                        } , function () {
                            alert("文件上传失败");
                        })
            }
        }
    });
</script>

错误记录:

  • 起初,我期望通过v-model对file控件和upload_files变量进行双向绑定。但是,发现files无法绑定到upload_files中。
    经过资料搜索,需要使用change事件来操作。(具体原因还没清楚,此处只做一个记录,待深入学习再做讨论)
  • 通过let files = event.target.files;拿到files后,起初我通过for ...in的方式遍历files,出错。

    对对象属性进行了遍历,js没系统学。
  • 起初,构建formData时,直接formData.append('files',this.upload_files);,出错。
    通过遍历this.upload_files,将每个file添加到表单中,即使key一样,也不会重置。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容