1. 程式人生 > >vue axios 實現上傳檔案

vue axios 實現上傳檔案

1 新建一個用來上傳檔案的axios,不同普通請求後臺的axios,因為上傳檔案不能手動設定請求頭

     var uploadAxios = axios.create({}),       Vue.prototype.$uploadAxios = uploadAxios;  

   注意: 不要設定請求頭headers: {'Content-Type': '......'},    因為上傳檔案時請求頭的mulpipart/formData格式需要boundary,  boundary是瀏覽器自動給請求頭內容新增的    如果設定了請求頭header, boundary就會被覆蓋,  然後上傳時就沒有資料傳到後臺和後臺報錯 “no multipart boundary was found

” ;

2  獲取檔案的值

<form>     <input type="file" @change="selectFile($event)">     <input type="button" @click="submittFile($event)"> </form> data: function(){        return { file: "", }  // 儲存檔案的值 } selectfile: function (event){        this.file = event.target.value  }

3 提交檔案到後臺        FormData型別其實是在XMLHttpRequest 2級定義的,它是為序列化表以及建立與表單格式相同的資料(當然是用於XHR傳輸)提供便利。

 submitFile: function (event){        event.preventDefault();        var formData = new FormData();         formData.append("file", this.file);   // 新增鍵值對到formData, 用append()方法新增方式;        formData.append('myname', 'rmy');

      // 上傳檔案不用設定請求頭, 瀏覽器會自動設定請求頭和boundary        this.$uploadAxios.post('url', formData).then(res=>{              console.log(res)        }).catch(err=>{            console.log(err);        }) }