前端预览XLSX
首先因为XLSX需要ArrayBuffer格式的数据,所以我们需要把我们获取到的数据先转换成ArrayBuffer.我所熟悉的数据格式是blob,所以我选择先转换成blob,在通过blob上的原生方法转换成ArrayBuffer.
            
            
              js
              
              
            
          
          downloadNameFile(record.storeFileName).then((res) => {
	// 这里的res返回的是blob类型的数据,通过arrayBuffer()可以转换成arrayBuffer类型的数据
   res.arrayBuffer().then(buffer => {
        const wb = xlsx.read(buffer);
        const wsname = wb.SheetNames[0];
        const ws = wb.Sheets[wsname];
        let html = xlsx.utils.sheet_to_html(ws);
        parentDom.innerHTML = html;
    })
})前端预览PDF
前端预览PDF我借鉴的是最简单的通过window.open()这个方法打开一个新标签页,预览PDF.你如果有更复杂的需求,可以去这个网站看一下PDF.js Express
            
            
              js
              
              
            
          
          const blob = new Blob(blobData, { type: application/pdf' });
const blobURL =window.URL.createObjectURL(blob);
window.open(blobURL);
window.URL.revokeObjectURL(blobURL);这里记住一定要设置blob的类型为application/pdf,这样才能正确在新标签页中预览.
前端下载文件
            
            
              js
              
              
            
          
          /**
 * 下载文件流
 * @param {*} data
 * @param {*} filename
 * @param {*} mime
 * @param {*} bom
 */
 export function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart) {
  const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
  const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });
  const blobURL = window.URL.createObjectURL(blob);
  const tempLink = document.createElement('a');
  tempLink.style.display = 'none';
  tempLink.href = blobURL;
  tempLink.setAttribute('download', filename);
  if (typeof tempLink.download === 'undefined') {
    tempLink.setAttribute('target', '_blank');
  }
  document.body.appendChild(tempLink);
  tempLink.click();
  document.body.removeChild(tempLink);
  window.URL.revokeObjectURL(blobURL);
}