前端根据url在线预览功能

文章目录

    • 加载脚本
    • WORD
    • excel
    • pdf
    • img
    • video

加载脚本


  // word
  await this.utils.loadScript('https://unpkg.com/promise-polyfill/dist/polyfill.min.js')
  await this.utils.loadScript('https://unpkg.com/jszip/dist/jszip.min.js')
  await this.utils.loadScript('https://unpkg.com/[email protected]/dist/docx-preview.min.js')

  // excel
  await this.utils.loadScript('https://unpkg.com/xlsx/dist/xlsx.full.min.js')

  // pdf
  await this.utils.loadScript('https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.9.179/pdf.min.js')

WORD

// 元素
<div id="viewModalContainer"></div>

// 方法
  const data = await fetch(url)
    .then((response) => response.blob())
    .then((res) => {
      this.$('dialog_lkw0jna2').show()
      docx.renderAsync(res, document.getElementById('viewModalContainer'), null, {
        // ignoreWidth: true,
        // ignoreHeight: true,
      }).then(result => {
        console.log('result', result)
      })
    })
  return data

excel

// 元素
<div id="excelContainer"></div>

// 方法
  const data = await fetch(url)
    .then((response) => response.arrayBuffer())
    .then((res) => {
      this.$('dialog_lkwbvqrc').show()
      const wb = XLSX.read(res);
      console.log('wb', wb)
      // const ws = wb.Sheets[wb.SheetNames[0]];
      // console.log('ws', ws)
      // const html = XLSX.utils.sheet_to_html(ws)
      let html = '';

      wb.SheetNames.forEach(function (name, index) {
        let ws = wb.Sheets[name];
        let str = XLSX.utils.sheet_to_html(ws, { header: 1, defval: '' });
        // 只截取table的内容
        let startNo = str.indexOf(``);let endNo = str.indexOf(`
`
); str = str.substring(startNo, endNo + ``.length); str = str.replace(/(\b(?:id|t|v)=".*?")/g, ''); str = str.replace('',`
`); html += str;})const dom = document.getElementById('excelContainer') dom.innerHTML = html })

pdf

// 有个canvas元素
<canvas id="pdfContainer"></canvas>

// 方法
  const loadingTask = pdfjsLib.getDocument(url)
  loadingTask.promise.then(res => {
    this.$('dialog_lkwbvqrg').show()
    // 获取 canvas 元素
    const canvas = document.getElementById('pdfContainer')

    res.getPage(1).then(function (page) {
      const viewport = page.getViewport({ scale: 1 });
      const context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;

      page.render({
        canvasContext: context,
        viewport: viewport
      });
    }).catch(error => {
      console.log('error:', error)
    })
  })

img

  • 根据使用的组件库直接预览
this.utils.previewImage({ current: rowData.path })

video

  • 新窗口打开
window.open(rowData.path)

你可能感兴趣的:(前端)