js文件下载

作者: zhao_ran | 来源:发表于2021-07-31 22:23 被阅读0次
    1.文件流下载

    根据后台接口文件流下载

    // ts文件
    export function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart) {
      const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
      const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename);
      } else {
        const blobURL = window.URL.createObjectURL(blob);
        const tempLink = document.createElement('a');
        tempLink.style.display = 'none';
        tempLink.href = blobURL;
        tempLink.setAttribute('download', filename);
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank');
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
      }
    }
    

    调用

    downloadByData('text content', 'testName.txt');
    
    2.文件地址下载

    根据文件地址下载文件

    export function openWindow(url, opt) {
      const { target = '__blank', noopener = true, noreferrer = true } = opt || {};
      const feature = [];
      noopener && feature.push('noopener=yes');
      noreferrer && feature.push('noreferrer=yes');
      window.open(url, target, feature.join(','));
    }
    export function downloadByUrl({
      url,
      target = '_blank',
      fileName,
    }) {
      const isChrome = window.navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
      const isSafari = window.navigator.userAgent.toLowerCase().indexOf('safari') > -1;
    
      if (/(iP)/g.test(window.navigator.userAgent)) {
        console.error('Your browser does not support download!');
        return false;
      }
      if (isChrome || isSafari) {
        const link = document.createElement('a');
        link.href = url;
        link.target = target;
    
        if (link.download !== undefined) {
          link.download = fileName || url.substring(url.lastIndexOf('/') + 1, url.length);
        }
    
        if (document.createEvent) {
          const e = document.createEvent('MouseEvents');
          e.initEvent('click', true, true);
          link.dispatchEvent(e);
          return true;
        }
      }
      if (url.indexOf('?') === -1) {
        url += '?download';
      }
    
      openWindow(url, { target });
      return true;
    }
    

    调用

     downloadByUrl({
              url: 'https://vebn.oss-cn-beijing.aliyuncs.com/vben/logo.png',
              target: '_self',
            });
    
    3.base64流下载

    base64流下载

    export function downloadByBase64(buf: string, filename: string, mime?: string, bom?: BlobPart) {
      const base64Buf = dataURLtoBlob(buf);
      downloadByData(base64Buf, filename, mime, bom);
    }
    export function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart) {
      const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
      const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename);
      } else {
        const blobURL = window.URL.createObjectURL(blob);
        const tempLink = document.createElement('a');
        tempLink.style.display = 'none';
        tempLink.href = blobURL;
        tempLink.setAttribute('download', filename);
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank');
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
      }
    }
    

    调用

    downloadByBase64(imgBase64, 'logo.png');
    
    4.图片Url下载

    图片Url下载,如果有跨域问题,需要处理图片跨域

    export function urlToBase64(url: string, mineType?: string): Promise<string> {
      return new Promise((resolve, reject) => {
        let canvas = document.createElement('CANVAS') as Nullable<HTMLCanvasElement>;
        const ctx = canvas!.getContext('2d');
    
        const img = new Image();
        img.crossOrigin = '';
        img.onload = function () {
          if (!canvas || !ctx) {
            return reject();
          }
          canvas.height = img.height;
          canvas.width = img.width;
          ctx.drawImage(img, 0, 0);
          const dataURL = canvas.toDataURL(mineType || 'image/png');
          canvas = null;
          resolve(dataURL);
        };
        img.src = url;
      });
    }
    
    export function downloadByOnlineUrl(url: string, filename: string, mime?: string, bom?: BlobPart) {
      urlToBase64(url).then((base64) => {
        downloadByBase64(base64, filename, mime, bom);
      });
    }
    export function downloadByBase64(buf: string, filename: string, mime?: string, bom?: BlobPart) {
      const base64Buf = dataURLtoBlob(buf);
      downloadByData(base64Buf, filename, mime, bom);
    }
    

    调用

    downloadByOnlineUrl(
              'https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5944817f47b8408e9f1442ece49d68ca~tplv-k3u1fbpfcp-watermark.image',
              'logo.png'
            );
    

    相关文章

      网友评论

        本文标题:js文件下载

        本文链接:https://www.haomeiwen.com/subject/wfnkvltx.html