Vue-resource上传图片到服务器

2019-12-05  本文已影响0人  topshi

首先,表单代码

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

错误记录:

上一篇下一篇

猜你喜欢

热点阅读