preface

We often encounter the need to download the file when writing code, if the background returns the file address, you can directly preview through window.open and download the local. If the file stream format is returned in the background, you can download the file in the following way

Code implementation

You can copy and use them directly, or encapsulate them as methods.

Axios ({method: 'get', url, responseType: "Blob ", // Response type is blob}).then(res => {new Response(res.data).text().then(text => { If (text.indexof ("message") === -1) { Let downloadName = res.headers['content-disposition'].split('filename="')[1] let blob = new blob ([res.data],  { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }); / / will let the server returns the file excel file url = window. Url. CreateObjectURL (blob); const link = document.createElement("a"); // create a tag link.href = url; link.download = downloadName link.click(); URL.revokeObjectURL(url); } else {console.log(json.parse (text).message)}})})Copy the code