vue axios 與 FormData 結合 提交檔案 上傳檔案

來源:互聯網
上載者:User

標籤:--   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 結合 提交檔案 上傳檔案

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.