vue axios 與 FormData 結合 提交文件 上傳文件

---再利用Vue、axios、FormData作上傳文件時,遇到一個問題,後臺雖然接收到請求,可是將文件類型識別成了字符串,因此,web端一直報500,結果是本身大意了。css

1.由於使用了new  FormData來操做表單,而且在測試模擬請求時,從消息頭裏看到的確實是表單提交【Content-Type: multipart/form-data】. 因此就沒有單獨在設置. ios

  結果後來加上了這個配置才能夠經過了。這裏的原理請參照轉發大神的原帖。web

這個必須設置:Content-Type: multipart/form-data

 

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

```

<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
來源:簡書

app

相關文章
相關標籤/搜索