前端使用axios實現(xiàn)下載文件功能的詳細過程
1、需求描述
在前后端分離開發(fā)的項目中,前端無論使用Vue或React哪種框架,發(fā)送HTTP請求都會使用Ajax異步請求的方式。在很多項目中都會選擇使用 axios 發(fā)送請求。但是在使用 axios 實現(xiàn)下載功能時,往往會出現(xiàn)以下問題。
當前端直接使用 axios 去請求下載文件的 api 接口時,狀態(tài)碼返回200,但是獲取的數(shù)據(jù)卻是一堆亂碼,效果如下:
2、問題分析
下載其實是瀏覽器的內(nèi)置事件,瀏覽器的 GET請求(frame、a)、 POST請求(form)具有如下特點:
- response 會交由瀏覽器處理;
- response 內(nèi)容可以為二進制文件、字符串等。
但是AJAX請求不一樣:
- response 會交由 Javascript 處理;
- response 內(nèi)容只能接收字符串才能繼續(xù)處理。
因此,AJAX本身無法觸發(fā)瀏覽器的下載功能。
3、解決方案
要在 axios 的 config 配置 responseType: ‘blob’ (非常關(guān)鍵),服務端讀取文件,以 content-type: ‘application/octet-stream’ 的格式返回前端,前端接收到數(shù)據(jù)后使用 Blob 來接收數(shù)據(jù),并且創(chuàng)建a標簽進行下載。
一個對象的類型取決于 responseType 的值,當值為 “blob”時表示 response 是一個包含二進制數(shù)據(jù)的 Blob 對象。
在使用 axios 發(fā)起請求前,首先了解一下 responseType 這個屬性是如何在 axios 中使用的。以 axios 最常用的 get 和 post 請求為例,這兩種請求方式在傳遞參數(shù)的時候也是不同的:
在get請求當中,config 是第二個參數(shù),而到了 post 里 config 變成了第三個參數(shù),這是傳遞 responseType 第一個需要注意的地方。
4、代碼實現(xiàn)
后端實現(xiàn)以 express 為例:
// 這里以express舉例 const fs = require('fs') const express = require('express') const bodyParser = require('body-parser') const app = express() app.use(bodyParser.urlencoded({extended: false})) app.use(bodyParser.json()) // 以post提交舉例 app.post('/info/download', function(req, res) { const filePath = './myfile/test.zip' const fileName = 'test.zip' res.set({ 'content-type': 'application/octet-stream', 'content-disposition': 'attachment;filename=' + encodeURI(fileName) }) fs.createReadStream(filePath).pipe(res) }) app.listen(3000)
前端在使用 axios 請求下載文件 api 接口時,一定要區(qū)分不同請求方法的使用,語法如下:
// axios設置reponseType的方式應該類似下面 const url = '/info/download' // get、delete、head 等請求 axios.get(url, {params: {}, responseType: 'blob'}) .then((res) => {}) .catch((err) => {}) // post、put、patch 等請求 axios.post(url, {...params}, {responseType: 'blob'}) .then((res) => {}) .catch((err) => {})
前端解析數(shù)據(jù)流,主要使用 Blob 對象來進行接收,示例代碼如下:
// 以之前的post請求舉例 axios.post(url, {...someData}, {responseType: 'blob'}) .then((res) => { const { data, headers } = res const fileName = headers['content-disposition'].replace(/\w+;filename=(.*)/, '$1') // 此處當返回json文件時需要先對data進行JSON.stringify處理,其他類型文件不用做處理 //const blob = new Blob([JSON.stringify(data)], ...) const blob = new Blob([data], {type: headers['content-type']}) let dom = document.createElement('a') let url = window.URL.createObjectURL(blob) dom.href = url dom.download = decodeURI(fileName) dom.style.display = 'none' document.body.appendChild(dom) dom.click() dom.parentNode.removeChild(dom) window.URL.revokeObjectURL(url) }).catch((err) => {})
如果后臺返回的流文件是一張圖片的話,前端需要將這張圖片直接展示出來,例如登錄時的圖片驗證碼,示例代碼如下:
axios.post(url, {...someData}, {responseType: 'blob'}) .then((res) => { const { data } = res const reader = new FileReader() reader.readAsDataURL(data) reader.onload = (ev) => { const img = new Image() img.src = ev.target.result document.body.appendChild(img) } }).catch((err) => {})
總結(jié)
到此這篇關(guān)于前端使用axios實現(xiàn)下載文件功能的文章就介紹到這了,更多相關(guān)axios下載文件功能內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript?Promise多并發(fā)問題的解決方法詳解
提起控制并發(fā),大家應該不陌生,這篇文章主要來和大家介紹一下JavaScript如何解決Promise多并發(fā)問題,感興趣的小伙伴可以跟隨小編一起學習一下2023-09-09JavaScript上傳文件時不用刷新頁面方法總結(jié)(推薦)
這篇文章主要介紹了JavaScript上傳文件時不用刷新頁面方法,用js+css代碼詳細介紹了操作過程,需要的朋友可以參考下2017-08-08