您好,登錄后才能下訂單哦!
使用axios怎么封裝一個(gè)上傳文件請求?很多新手對此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
axios 和 ajax 都支持異步請求,兩者使用方法大同小異,在此使用 axios 上傳文件的請求。使用的時(shí)候只需要在響應(yīng)的 vue 組件中引入就可以。
import Vue from 'vue'; import VueCookie from 'vue-cookie'; import axios from 'axios'; // import toastr from '../assets/toastr.min'; // Vue.use(axios) let http = {}; // let _baseURL = '/vpaas' let _baseURL = 'http://localhost:8080/vpaas' let ContentType = "application/json"; let uploadFileType = "multipart/form-data"; http.baseURL = _baseURL; /** * 上傳文件的請求 * @param url * @returns {AxiosPromise} */ http.uploadFile = function (url, data) { let config = { //請求的接口,在請求的時(shí)候,如axios.get(url,config);這里的url會覆蓋掉config中的url url: url, //基礎(chǔ)url前綴 baseURL: _baseURL, transformResponse: [function (data1) { var data = data1; if (typeof data1 == "string") { data = JSON.parse(data1); } //這里提前處理返回的數(shù)據(jù); if (data.message && (data.data === 'login.invalid.token')) { window.localStorage.removeItem("access-user"); alert("超時(shí)請重新登陸"); window.location.href = '/'; } return data; }], //請求頭信息 headers: {'access-user': window.localStorage.getItem('access-user'), 'Content-Type': uploadFileType}, //跨域請求時(shí)是否需要使用憑證 withCredentials: true, // 返回?cái)?shù)據(jù)類型 responseType: 'json', //default }; return axios.post(url, data, config); };
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。