download.ts 977 B

123456789101112131415161718192021222324
  1. import download from 'downloadjs';
  2. import { ElMessage } from 'element-plus';
  3. const downloadFile = (res: any, fileName: string = '导出日志.xlsx') => {
  4. // 判断是不是返回的是json,是json说明报错了,否则返回的是文本流
  5. const decoder = new TextDecoder('utf-8');
  6. const text = decoder.decode(res.data);
  7. try {
  8. const errJson = JSON.parse(text)
  9. if (errJson.message) {
  10. ElMessage.closeAll()
  11. ElMessage.error(errJson.message)
  12. }
  13. } catch {
  14. // 用split是避免多次取值重复都好分割的情况,比如
  15. // attachment; filename="2022-12-06 21:34:35-SysLoginLog.xlsx", attachment; filename="2022-12-06 21:34:35-SysLoginLog.xlsx"
  16. const lastFileName = res.headers['content-disposition'] ? res.headers['content-disposition'].split(',')[0].replaceAll('attachment; filename="', '').replaceAll('"', '') : fileName;
  17. download(res.data, lastFileName, res.headers['content-type']);
  18. }
  19. }
  20. export default downloadFile