重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
本篇文章為大家展示了怎么在vue中使用axios下載文件,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
功能:點(diǎn)擊導(dǎo)出按鈕,提交請(qǐng)求,下載excel文件;
第一步:跟后端童鞋確認(rèn)交付的接口的response header設(shè)置了
以及返回了文件流。
第二步:修改axios請(qǐng)求的responseType為blob,以post請(qǐng)求為例:
axios({ method: 'post', url: 'api/user/', data: { firstName: 'Fred', lastName: 'Flintstone' }, responseType: 'blob' }).then(response => { this.download(response) }).catch((error) => { })
第三步:請(qǐng)求成功,拿到response后,調(diào)用download函數(shù)(創(chuàng)建a標(biāo)簽,設(shè)置download屬性,插入到文檔中并click)
methods: { // 下載文件 download (data) { if (!data) { return } let url = window.URL.createObjectURL(new Blob([data])) let link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', 'excel.xlsx') document.body.appendChild(link) link.click() } }
下面在通過(guò)實(shí)例代碼看下vue中使用axios
1.安裝axios
npm:
$ npm install axios -S
cdn:
2.配置axios
在項(xiàng)目中新建api/index.js文件,用以配置axios
api/index.js
import axios from 'axios'; let http = axios.create({ baseURL: 'http://localhost:8080/', withCredentials: true, headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' }, transformRequest: [function (data) { let newData = ''; for (let k in data) { if (data.hasOwnProperty(k) === true) { newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&'; } } return newData; }] }); function apiAxios(method, url, params, response) { http({ method: method, url: url, data: method === 'POST' || method === 'PUT' ? params : null, params: method === 'GET' || method === 'DELETE' ? params : null, }).then(function (res) { response(res); }).catch(function (err) { response(err); }) } export default { get: function (url, params, response) { return apiAxios('GET', url, params, response) }, post: function (url, params, response) { return apiAxios('POST', url, params, response) }, put: function (url, params, response) { return apiAxios('PUT', url, params, response) }, delete: function (url, params, response) { return apiAxios('DELETE', url, params, response) } }
這里的配置了POST、GET、PUT、DELETE方法。并且自動(dòng)將JSON格式數(shù)據(jù)轉(zhuǎn)為URL拼接的方式
同時(shí)配置了跨域,不需要的話將withCredentials設(shè)置為false即可
并且設(shè)置了默認(rèn)頭部地址為:http://localhost:8080/,這樣調(diào)用的時(shí)候只需寫(xiě)訪問(wèn)方法即可
3.使用axios
注:PUT請(qǐng)求默認(rèn)會(huì)發(fā)送兩次請(qǐng)求,第一次預(yù)檢請(qǐng)求不含參數(shù),所以后端不能對(duì)PUT請(qǐng)求地址做參數(shù)限制
首先在main.js中引入方法
import Api from './api/index.js'; Vue.prototype.$api = Api;
然后在需要的地方調(diào)用即可
this.$api.post('user/login.do(地址)', { "參數(shù)名": "參數(shù)值" }, response => { if (response.status >= 200 && response.status < 300) { console.log(response.data);\\請(qǐng)求成功,response為成功信息參數(shù) } else { console.log(response.message);\\請(qǐng)求失敗,response為失敗信息 } });
上述內(nèi)容就是怎么在vue中使用axios下載文件,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。