zoukankan      html  css  js  c++  java
  • 下载文件方法

    /**
     * 下载文件
     * @param content 响应体
     * @param fileName 文件名
     */
    export function download(content, fileName) {
      const blob = new Blob([content]) //创建一个类文件对象:Blob对象表示一个不可变的、原始数据的类文件对象
      const url = window.URL.createObjectURL(blob) //URL.createObjectURL(object)表示生成一个File对象或Blob对象
      let dom = document.createElement('a') //设置一个隐藏的a标签,href为输出流,设置download
      dom.style.display = 'none'
      dom.href = url
      dom.setAttribute('download', fileName) //指示浏览器下载url,而不是导航到它;因此将提示用户将其保存为本地文件
      document.body.appendChild(dom)
      dom.click()
    }
    

     

    ajax的回调

     // 获取文件名,保存下载内容
      const contentDisposition =
        resp.headers && resp.headers['content-disposition']
        let fileName = 'unknown'
        if (contentDisposition) {
            fileName = window.decodeURI(resp.headers['content-disposition'].split('=')[1],)
      }
       download(resp.data, fileName)            
    

      

    *******************************************************************************************'

    使用file-saver

    import {saveAs} from 'file-saver';
    
     downLoadFile(item) {
          const {url} = item;
          const getUrlFileName = url.match(/([^/]+)(.[^.]*)(?=?|$)/)[0];
          // 下载文件ajax
          const downLoadFileMethodPromise = () => {
            return new Promise((resolve, reject) => {
              const xhr = new XMLHttpRequest();
              xhr.open('get', url);
              xhr.responseType = 'blob';
              xhr.onload = function() {
                saveAs(xhr.response, getUrlFileName);
              };
              xhr.onerror = err => reject && reject(err);
              xhr.send();
            });
          };
    
          downLoadFileMethodPromise().catch(() => {
            this.$message({
              message: '下载失败!',
              type: 'error',
            });
          });
        },
    

      

  • 相关阅读:
    学习了一下调色理论
    几个同步软件
    慢性咽炎
    flash行情
    C#创建Windows服务
    .net下 foreach 与 for 的效率比较测试
    HTML服务器控件与Web服务器控件的区别
    c#遍历HashTable
    ASP.NET中Server与Request对象的方法
    .net内存回收与Dispose﹐Close﹐Finalize方法
  • 原文地址:https://www.cnblogs.com/usebylgb/p/12981708.html
Copyright © 2011-2022 走看看