Home > Article > Web Front-end > Use axios to implement the download function through vue.js (detailed tutorial)
Below I will share with you an example of using vue.js to implement the download function using axios. It has a good reference value and I hope it will be helpful to everyone.
This article mainly comes from an answer on Zhihu. The red part here has been processed by myself. Although it is small, it is a very useful code.
I have to answer itaxios How to intercept the get request and download the file .
The reason why Ajax cannot download files
The browser's GET (frame, a) and POST (form) requests have the following characteristics:
The response will be processed by the browser
The response content can be binary files, strings, etc.
##Ajax requests have the following characteristics:
The response will be processed by Javascript The response content can only be a string Therefore, Ajax itself cannot trigger the browser's download function.Axios intercepts the request and implements the download
In order to download the file, we usually use the following steps:Send a request
Get the responseUse the response to determine whether the return is a fileIf it is a file, insert a frame into the pageUse frame to implement Browser's get downloadWe can add an interceptor for axios:
import axios from 'axios' // download url const downloadUrl = url => { let iframe = document.createElement('iframe') iframe.style.display = 'none' iframe.src = url iframe.onload = function () { document.body.removeChild(iframe) } document.body.appendChild(iframe) } // Add a response interceptor axios.interceptors.response.use(c=> { // 处理excel文件 if (res.headers && (res.headers['content-type'] === 'application/x-msdownload' || res.headers['content-type'] === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) { downloadUrl(res.request.responseURL) <span style="color:#ff0000;"> res.data=''; res.headers['content-type'] = 'text/json' return res;</span> } ... return res; }, error => { <span style="color:#ff0000;">// Do something with response error return Promise.reject(error.response.data || error.message)</span> }) export default axiosAfter that, we can download the file through the get request in axios. The above is what I compiled for everyone. I hope it will be helpful to everyone in the future. Related articles:
nodejs implements a super simple method to generate QR codes
nodejs mongodb aggregate cascade query operation example
Solve the problem that the DOM operation of the vue page does not take effect
The above is the detailed content of Use axios to implement the download function through vue.js (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!