后端接口返回文件流,前端實現(xiàn)docx/pdf/excel等類型文件的下載功能
最近遇到一個需求,在后端返回文件流后前端需要實現(xiàn)導出docx類型的文件。在網(wǎng)上查看了一些資料總結(jié)了兩種比較常用的方法。
方法一:前端接收到后端返回的數(shù)據(jù)后將返回結(jié)果轉(zhuǎn)換為Blob類型,再進行操作。
1、封裝接口
注意:接口需要添加 responseType: “blob”,否則會出現(xiàn)文件下載后無法打開或者損壞的情況。
export function downloadFile(id) {
return request({
url: "/project/approval/getWord/" + id,
responseType: "blob",
method: "post",
})
}
2、轉(zhuǎn)換數(shù)據(jù)格式
導出word文件,需要在創(chuàng)建blob對象時傳入第二個參數(shù),并將type設(shè)置為“application/vnd.openxmlformats-officedocument.wordprocessingml.document”
handleDownload() {
downloadPromise(this.ids[0]).then((res) => {
let blob = new Blob([res], {
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
let objectUrl = URL.createObjectURL(blob);
let link = document.createElement("a");
let fname = "文件名稱";
link.href = objectUrl;
link.setAttribute("download", fname);
document.body.appendChild(link);
link.click();
})
.catch(() => {
this.$modal.msgWarning("文件下載出錯!");
});
},
方法二:封裝download方法(修改若依前端導出文件方法)
1、封裝download方法
//該方法需要接受四個參數(shù)url:后端請求地址,params:請求參數(shù),filename文件名稱,contentType:content-type類型。
export function download(url, params, filename, config, contentType) {
downloadLoadingInstance = Loading.service({ text: "正在下載數(shù)據(jù),請稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
return service.post(url, params, {
transformRequest: [(params) => { return tansParams(params) }],
//這里可以根據(jù)導出文件的類型來傳相應的Content-Type值
headers: { 'Content-Type': contentType ? contentType : 'application/x-www-form-urlencoded' },
responseType: 'blob',
...config
}).then(async (data) => {
const isBlob = blobValidate(data);
if (isBlob) {
const blob = new Blob([data])
saveAs(blob, filename)
} else {
const resText = await data.text();
const rspObj = JSON.parse(resText);
const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
Message.error(errMsg);
}
downloadLoadingInstance.close();
}).catch((r) => {
console.error(r)
Message.error('下載文件出現(xiàn)錯誤,請聯(lián)系管理員!')
downloadLoadingInstance.close();
})
}
2、調(diào)用download方法
handleDownload() {
this.download(
"/project/approval/getWord/" + this.ids[0],
//沒有請求參數(shù)則傳空對象
{},
//文件名稱可以自行設(shè)置
`type_${new Date().getTime()}.docx`,
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
);
},
相關(guān)資料
在網(wǎng)上查找了一些關(guān)于 content-type 的編碼格式以及responseType。文章來源:http://www.zghlxwxcb.cn/news/detail-812952.html
.doc application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.rtf application/rtf
.xls application/vnd.ms-excel application/x-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.pps application/vnd.ms-powerpoint
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.pdf application/pdf
.swf application/x-shockwave-flash
.dll application/x-msdownload
.exe application/octet-stream
.msi application/octet-stream
.chm application/octet-stream
.cab application/octet-stream
.ocx application/octet-stream
.rar application/octet-stream
.tar application/x-tar
.tgz application/x-compressed
.zip application/x-zip-compressed
.z application/x-compress
.wav audio/wav
.wma audio/x-ms-wma
.wmv video/x-ms-wmv
.mp3 .mp2 .mpe .mpeg .mpg audio/mpeg
.rm application/vnd.rn-realmedia
.mid .midi .rmi audio/mid
.bmp image/bmp
.gif image/gif
.png image/png
.tif .tiff image/tiff
.jpe .jpeg .jpg image/jpeg
.txt text/plain
.xml text/xml
.html text/html
.css text/css
.js text/javascript
.mht .mhtml message/rfc822
"" responseType 設(shè)為空字符串與設(shè)置為"text"相同,默認類型
"text" 返回的是包含在 DOMString 對象中的文本。
"document" 返回的是一個 HTML Document 或 XML XMLDocument
"arraybuffer" 返回的是一個包含二進制數(shù)據(jù)的 JavaScript ArrayBuffer
"blob" 返回的是一個包含二進制數(shù)據(jù)的 Blob 對象
"json" 返回的是一個 JavaScript 對象 。這個對象是通過將接收到的數(shù)據(jù)類型視為 JSON 解析得到的。
"ms-stream" 返回的是下載流的一部分 ;此響應類型僅允許下載請求,并且僅受Internet Explorer支持
總結(jié)
使用第一種方法時遇到的坑,沒有在接口api設(shè)置responseType: “blob”,導致文件下載成功后無法打開。最后,在前端開發(fā)過程中經(jīng)常會遇到文件導出的需求,在這里總結(jié)一下用到過的方法以便在下次使用時可以直接復用。文章來源地址http://www.zghlxwxcb.cn/news/detail-812952.html
到了這里,關(guān)于后端接口返回文件流,前端實現(xiàn)docx/pdf/excel等類型文件的導出功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!