UNPKG

sll-utils

Version:

一个js处理工具

72 lines (68 loc) 1.97 kB
export const downLoadFile = (response:any,fileName: string, type: string = 'docx') => { try { let _type: string = '' switch (type) { case 'pdf': _type = 'application/pdf'; break case 'xls': _type = 'application/vnd.ms-excel'; break case 'xlsx': _type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; break case 'doc': _type = 'application/msword'; break case 'docx': _type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; break case 'txt': _type = 'text/plain'; break case 'svg': _type = 'image/svg+xml'; break case 'jpg': case 'jpeg': _type = 'image/jpeg'; break case 'png': _type = 'image/png'; break default: _type = 'application/octet-stream'; break } // 创建一个 URL 对象 const url = window.URL.createObjectURL(new Blob([response], { type: _type })); const link = document.createElement('a'); link.href = url; link.setAttribute('download', `${fileName}.${type}`); // 设置下载文件的名称 document.body.appendChild(link); link.click(); // 释放 URL 对象 window.URL.revokeObjectURL(url); } catch (error) { console.error('下载文件失败:', error); } }; /** * * @param value 得到数据类型 */ export function getType(value: any) { const type = Object.prototype.toString.call(value) return type.replace(/(\[)|(\])/g, '').split(' ')[1] } // blob 转 Base64 export function blobToBase64(blob: any) { return new Promise((resolve, reject) => { const reader: any = new FileReader(); reader.onload = () => resolve(reader.result.split(',')[1]); reader.onerror = reject; reader.readAsDataURL(blob); }); }