Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue-预览文件 #51

Open
PleaseStartYourPerformance opened this issue Sep 9, 2021 · 0 comments
Open

Vue-预览文件 #51

PleaseStartYourPerformance opened this issue Sep 9, 2021 · 0 comments

Comments

@PleaseStartYourPerformance
Copy link
Owner

// 附件预览js
// 包含文件类型的轮询
import { Component, Vue} from "vue-property-decorator";
// import {json2str} from 'src/common/assets/js/common-func'
import { XrxsStringUtils } from "@xin/xin-core";
import {namespace } from "vuex-class";
import constData from "src/common/constant/const-data"

const moduleBase = namespace("moduleBase");
type fileItem = {
  name: string;
  key: string;
  url: string;
};
@Component({})
export default class filePreviewMixin extends Vue{
  @moduleBase.Action("getFilePreview") public getFilePreview!: Function;
  pollingId:number|undefined = 0;

  // cdn上的文件预览地址
  targetOrigin: string = constData.previewOriginUrl;
  directPreviewFormat: string[] = ['pdf', 'et', 'xls', 'xlt', 'xlsx', 'xlsm', 'xltx', 'xltm', 'csv', 'doc', 'docx', 'txt', 'dot', 'wps', 'wpt', 'dotx', 'docm', 'dotm', 'rtf', 'ppt', 'pptx', 'pptm', 'ppsx', 'ppsm', 'pps', 'potx', 'potm', 'dpt', 'dps']

  startPolling (fileKey:string,successPreviewCb:Function) {
    const t:any = this;
    t.pollingId = 0; //每次预览一个新的文件  可以开始
    async function timerFn(){
      let res;
      console.log("t.pollingId",t.pollingId)
      try{
        res = await t.getFilePreview({"key":fileKey,"asyn": 1});
      }catch (e) {
        t.$message.error(e)
        return
      }
      if(!res.status){
        t.$message.error(res.message)
        return
      }
      let previewData = res.data
      if(t.pollingId === undefined) return
      // status: 1,2,3 --> 解析中,解析成功,解析失败
      if(previewData.status === 1){
        t.pollingId = setTimeout(()=>{
          timerFn()
        },1000)
      }else if(previewData.status === 2){
        t.clearTimer() // 预览成功 清空定时器
        successPreviewCb(previewData)
      }else{
        t.clearTimer() // 预览失败  清空定时器
        t.$message.error(res.message)
      }
    }
    timerFn()
  }
  clearTimer(){
    clearTimeout(this.pollingId)
    this.pollingId = undefined;
  }

  imgFilePreview(file:fileItem){
    const xhr = new XMLHttpRequest();
    xhr.open('GET', file.url);
    xhr.responseType = 'blob';
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        const fileUrl:string = URL.createObjectURL(this.response);
        let popwin:any = window.open(fileUrl)
        popwin.onload = function () {
          this.document.title = "文件预览"
          URL.revokeObjectURL(fileUrl);
        }
      }
    }
    xhr.send()
  }
  // 预览
  openPreview(file:fileItem, cb?: () => void){
    const t:any = this;
    let fileName:string = file.url || file.name;
    let fileFormat:string = fileName&&fileName.substr(fileName.lastIndexOf('.')+1).toLowerCase();
    let targetOrigin = t.targetOrigin;
    // 轮询成功之后的打开预览
    let loading: any = null
    function successPreviewCb(previewData:any){
      loading && loading.close()
      t.$http({
        url: '/support/ajax-preview-v2file',
        method: 'post',
        data: {key: previewData.pdfKey || previewData.key}
      }).then((reply: any)=>{
        const res: any = reply.data
        if(!res.status){
          t.$message.error(res.message)
          return
        }
        const xhr = new XMLHttpRequest();
        xhr.open('GET', targetOrigin);
        xhr.responseType = 'blob';
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4 && xhr.status === 200) {
            const fileUrl:string = URL.createObjectURL(this.response);
            const popupwin:any = window.open(fileUrl)
            popupwin.onload = function () {
              popupwin.postMessage({
                XRXS: true,
                previewUrl: res.data.previewUrl,
                accessToken: res.data.accessToken,
              }, '*');
              URL.revokeObjectURL(fileUrl);
            }
            cb && cb()
          }
        }
        xhr.send()
      })
    }

    if(fileFormat === "jpg" || fileFormat === "png" || fileFormat === "bmp" || fileFormat === "jpeg"){
      t.imgFilePreview(file)
    }else if(this.directPreviewFormat.includes(fileFormat)){
      successPreviewCb(file)
    }else{
      loading = t.$loading({
        target: '.main-content',
        fullscreen: false,
        lock: true,
        text: "预览加载中",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.8)"
      });
      t.startPolling(file.key,successPreviewCb)
    }
  }

  deactivated() {
    // 组件离开 清除定时器
    this.clearTimer()
    console.log("---deactivated----",this.pollingId)
    this.$destroy();
  }
}

其中- '/support/ajax-preview-v2file'接口返回为一下值

image

使用组件

 @click="openPreview(file)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant