Example of using axios to download vue. js, vue. jsaxios
This article mainly comes from zhihu's answer. Here, the red part is used for its own processing. Although there are few of them, there are several useful codes.
I have to answer this question.How does axios intercept get requests and download files?.
Why Ajax cannot download files
Browser GET (frame, a) and POST (form) requests have the following features:
Response will be handled by the browser
Response content can be binary files, strings, etc.
Ajax requests have the following features:
Response will be handled by Javascript
The response content can only be a string
Therefore, Ajax itself cannot trigger the download function of the browser.
Axios intercepts requests and implements download
To download an object, follow these steps:
Send request
Get response
Use response to determine whether the returned result is a file
If it is a file, insert the frame in the page.
Use frame to implement get download in the browser
We can add an interceptor for axios:
Import axios from 'axios '// download urlconst 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 interceptoraxios. interceptors. response. use (c => {// process the excel file 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 axios
Then we can download the object through get request in axios.
The above example of downloading using axios in vue. js is a small part of the Content shared by Alibaba Cloud. I hope you can give us a reference and provide more support to the customer center.