handleDownloadFile/index.js

/**
 * 功能:下载文件的方法
 * @param {object} option - 配置对象
 * @param {string} url-option - 下载地址
 * @param {string} filename-option - 下载后的文件名
 * @returns {undefined} undefined
 */

const handleDownloadFile = ({ url, filename = '', triggerDelay = 100, removeDelay = 6000 }) => {
    const paramsReg = /\?.+$/;
    const formatReg = /\.\w+$/;
    const hasParams = paramsReg.test(url); // 是否有参数
    const hasFormat = formatReg.test(filename); // 是否有文件格式
    const fileFormatMatchResult = url.replace(paramsReg, '').match(formatReg);
    const customFilename = (hasFormat || !fileFormatMatchResult) ? filename : `${filename}${fileFormatMatchResult[0]}`; // 自定义文件名
    const customUrl = (filename && fileFormatMatchResult) ? `${url}${hasParams ? '&' : '?'}name=${customFilename}` : url; // 加上name参数,用于自定义文件名
  
    // console.log(customUrl, 'customUrl')
  
    //动态添加iframe,设置src,然后删除
    window.setTimeout(() => {
      const frame = document.createElement("iframe");
  
      frame.src = customUrl;
      frame.style.display = "none";
  
      document.body.appendChild(frame);
  
      frame.onload = () => {
        console.error('下载文件失败:', customUrl);
      };
  
      window.setTimeout(function() {
        frame.remove();
      }, removeDelay);
    }, triggerDelay);
  }
  
  export default handleDownloadFile;