根据Blob流(即后端的Stream文件类型格式)下载文件
接口调用
先看看这个接口的返回值
前端处理
//根据文件后缀名来映射Blob Type const typeDic = { docx: 'application/msword', doc: 'application/msword', bin: 'application/octet-stream', exe: 'application/octet-stream', so: 'application/octet-stream', dll: 'application/octet-stream', pdf: 'application/pdf', ai: 'application/postscript', xls: 'application/vnd.ms-excel', xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ppt: 'application/vnd.ms-powerpoint', dir: 'application/x-director', js: 'application/x-javascript', swf: 'application/x-shockwave-flash', xhtml: 'application/xhtml+xml', xht: 'application/xhtml+xml', zip: 'application/zip', mid: 'audio/midi', midi: 'audio/midi', mp3: 'audio/mpeg', rm: 'audio/x-pn-realaudio', rpm: 'audio/x-pn-realaudio-plugin', wav: 'audio/x-wav', bmp: 'image/bmp', gif: 'image/gif', jpeg: 'image/jpeg', jpg: 'image/jpeg', png: 'image/png', css: 'text/css', html: 'text/html', htm: 'text/html', txt: 'text/plain', xsl: 'text/xml', xml: 'text/xml', mpeg: 'video/mpeg', mpg: 'video/mpeg', avi: 'video/x-msvideo', movie: 'video/x-sgi-movie' }; /** * 根据Blob下载文件(Blob即后端的Stream文件类型格式) * @params fileName文件名,比如‘2021届学生.xlsx’ * @params fileBlob文件 */ export const downFileBlob = (fileName, fileBlob) => { const fileNameGroup = fileName.split('.'); const fileType = fileNameGroup[fileNameGroup.length - 1].toLowerCase(); const blob = new Blob([fileBlob], { type: typeDic[fileType] });//处理文档流 const elink = document.createElement('a'); elink.download = fileName; elink.style.display = 'none'; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href); // 释放URL 对象 document.body.removeChild(elink); } /* * 下载按钮点击 */ const btnClick = async () => { const result = await axios({ url: 'http://localhost:8000/api/v1/excel/template', params: { sceneId: 527 }, responseType: 'blob' // 一定要加,不然下载的文件打开乱码 }); // 响应头里的 content-disposition: attachment;filename=2021届学生.xlsx const fileName = result.headers['content-disposition'].replace('attachment;filename=', ''); downFileBlob(fileName, result.data); };