Bootstrap

vue下载、预览文件流

预览

封装js文件


import axios from 'axios';
//预览文件流
export async function previewImage(fileAddress) {
  const res = await axios({
    method: 'post',
    data: { downloadUrl: fileAddress }, //额外参数,看接口是否需要
    headers: { Authorization: 'Bearer ' + getToken() },
    url: 'xxxxxx', // 请求地址
    responseType: 'blob', // 设置接收格式为blob格式
  });
  return new Promise((resolve, reject) => {
    if (res && res.data && res.data.size) {
      let blob = new Blob([res.data], { type: 'image/jpeg' });
      const imageUrl = URL.createObjectURL(blob);
      resolve(imageUrl);
    }
  });
}

页面调用
  import { previewImage } from '@/utils/index';
//预览附件类型
  link(row) {
     previewImage(row.fileAddress).then((res) => {
       if (res) {
         this.dialogVisible = true;
         this.dialogImageUrl = res;
       }
     })
  },

下载

//下载附件
export function downloadurl(fileAddress, fileName) {
//OBSUploadDownload  是我本地封装的api接口,根据自己项目更换,api要加上responseType: 'blob',属性
  OBSUploadDownload({ downloadUrl: fileAddress }).then((res) => {
    const content = res;
    const blob = new Blob([content], {
      // 下载的文件格式自己在这边更改type的值就好了
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    });
    if ('download' in document.createElement('a')) {
      const elink = document.createElement('a');
      elink.download = fileName;
      elink.style.display = 'none';
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href);
      document.body.removeChild(elink);
    } else {
      navigator.msSaveBlob(blob, fileName);
    }
  });
}

页面调用
  import { downloadurl } from '@/utils/downloadFile';
//下载预览附件
 downloadFile(row) {
   downloadurl(row.fileAddress, row.fileName);
 },
;