tools.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { Loading } from 'element-ui';
  2. /**
  3. * 从 HTTP 头的 Content-Disposition 字段中提取文件名
  4. * @param {string} contentDisposition - HTTP 头的 Content-Disposition 字段值
  5. * @returns {string|null} 提取的文件名,若未找到则返回 null
  6. */
  7. export function ExtractFilename(contentDisposition) {
  8. if (!contentDisposition) return null;
  9. // 匹配 filename= 后面的内容(直到分号或字符串结束)
  10. const match = contentDisposition.match(/filename=([^;]+)/i);
  11. if (!match) return null;
  12. let filename = match[1].trim();
  13. // 去除可能的引号
  14. if (filename.startsWith('"') && filename.endsWith('"')) {
  15. filename = filename.slice(1, -1);
  16. }
  17. try {
  18. // URL 解码
  19. return decodeURIComponent(filename);
  20. } catch (e) {
  21. console.warn('URL解码失败,返回原始文件名:', e);
  22. return filename;
  23. }
  24. }
  25. /**
  26. * 触发浏览器下载文件
  27. * @param {Blob} blob - 要下载的文件的 Blob 对象
  28. * @param {string} fileName - 下载时使用的文件名
  29. */
  30. export function DownloadFile(blob, fileName) {
  31. const url = window.URL.createObjectURL(blob);
  32. const link = document.createElement('a');
  33. link.href = url;
  34. link.download = fileName;
  35. link.click();
  36. window.URL.revokeObjectURL(url);
  37. link.remove();
  38. }
  39. /**
  40. * 创建一个加载中实例
  41. * @param {Object} options - 加载中配置选项
  42. * @returns {Object} 加载中实例
  43. */
  44. export function CreateLoadingInstance(options) {
  45. options = Object.assign({
  46. lock: true,
  47. text: '正在处理...',
  48. spinner: 'el-icon-loading',
  49. background: 'rgba(0, 0, 0, 0.7)'
  50. }, options || {});
  51. return Loading.service(options);
  52. }