vue axios 与 FormData 结合 提交文件 上传文件

---再利用Vue、axios、FormData做上传文件时,遇到一个问题,后台虽然接收到请求,但是将文件类型识别成了字符串,所以,web端一直报500,结果是自己大意了。

1.因为使用了new  FormData来操作表单,并且在测试模拟请求时,从消息头里看到的确实是表单提交【Content-Type: multipart/form-data】. 所以就没有单独在设置. 

  结果后来加上了这个配置才可以通过了。这里的原理请参照转发大神的原帖。

这个必须设置:Content-Type: multipart/form-data

2.结合Vue、axios、FormData使用的例子:

```

<template>

     <div id="sample">

        <!--accept定义接收的文件类型,这里只接受图片-->

        <input id="fileinput" @change="uploading($event)" type="file" accept="image/*">

           <button  @click="submit($event)"></button>

        

     </div>

</template>

<script>

export default {

  name: 'sample',

  data () {

    return {

        file:'',

        src:''

    };

  },

  methods:{

   uploading(event){

   this.file = event.target.files[0];//获取文件

       var windowURL = window.URL || window.webkitURL;

        this.file = event.target.files[0];

        //创建图片文件的url

        this.src = windowURL.createObjectURL(event.target.files[0]);

   },

   submit(){

   event.preventDefault();//取消默认行为

   let formdata = new FormData();

   formdata.append('file',this.file);

//此处必须设置为  multipart/form-data

let config = {

            headers: {

                'Content-Type': 'multipart/form-data'  //之前说的以表单传数据的格式来传递fromdata

            }

        };

        this.$http.post('/upload', formData, config).then( (res) => {

       //做处理

    }).catch((error) =>{

 

    });

   }

  }

};

</script>

<style lang="css" scoped>

</style>

```


转发源:
作者:johe_jianshu
链接:https://www.jianshu.com/p/84e94cc446c0
來源:简书

原文地址:https://www.cnblogs.com/ANCAN-RAY/p/8533088.html