標籤:-- creat 類比請求 sub rip multipart pos prevent pen
---再利用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-datalet 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
來源:簡書
vue axios 與 FormData 結合 提交檔案 上傳檔案