网页文件点击不预览直接下载

对于想在浏览器中点击直接下载,而非在浏览器中预览的场景,实用的 JS 函数;
比如网页txt文件点击不预览直接下载

思路:创建 Element,获取 blob 数据,利用 window.URL.createObjectURL() 读取并指定给 a.href,插入 手动触发下载;


// 静态资源服务器地址
const staticServer = 'http://xx.xxx.xxx.xxx:xxxxx';

// 点击已上传的文件
function onPreview(file) {
  if (file && file.path) {
    let url = `${staticServer}${file.path}`
    let isTxt = isFileType(file.path, 'txt');
    // txt直接下载,避免新窗口打开
    if (isTxt) {
      let name = file.name || file.path.split('/').slice(-1)[0] || ''
      exportFile(url, name)
    } else {
      window.open(url)
    }
  }
},

// 判断文件类型
function isFileType(url, fileTypeList = '') {
    const type = url.split('.').at(-1);
    if(Array.isArray(fileTypeList)){
        return fileTypeList.includes(type)
    } else {
        return type === fileTypeList
    }
},

// 导出文件
function exportFile(url, fileName) {
  function createObjectURL(object) {
    return window.URL ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object)
  }
  let xhr = new XMLHttpRequest();
  let formData = new FormData();
  xhr.open('get', url);
  xhr.setRequestHeader('Auth-User-Token', localStorage.getItem('token'));
  xhr.responseType = 'blob';
  xhr.onload = function (e) {
    if (this.status === 200) {
      let blob = this.response;
      let newFileName = `${fileName}`;
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, newFileName)
      } else {
        let a = document.createElement('a');
        let url = createObjectURL(blob);
        a.href = url;
        a.download = newFileName;
        document.body.append(a);
        a.click();
        window.URL.revokeObjectURL(url);
      }
    }
  };
  xhr.send(formData)
};

// 导出文件,不做兼容
const exportFile2 = (file) => {
  let link = document.createElement('a')
  let url = staticServer + file.path
  fetch(url).then(res => res.blob()).then(blob => {
    let urlObj = URL.createObjectURL(blob);
    link.href = urlObj;
    link.download = ''
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(urlObj);
  })
};

你可能感兴趣的:(网页文件点击不预览直接下载)