前端下载后台传入的pdf base64格式的文件


1、下载文件封装downloadFile.js

// 图片转blob
function imgURLtoBlob(dataurl) {
  const arr = dataurl.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

// pdf转blob
function pdfBase64ToBlob(dataUrl) {
  var bstr = atob(dataUrl)
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: 'pdf' })
}

function downloadFile(url, name) {
  const a = document.createElement('a')
  a.setAttribute('href', url)
  const fileName = name + '.pdf'
  a.setAttribute('download', fileName)
  a.setAttribute('target', '_blank')
  const clickEvent = document.createEvent('MouseEvents')
  clickEvent.initEvent('click', true, true)
  a.dispatchEvent(clickEvent)
}

export function downloadFileByBase64(url, name) {
  if (url) {
    const myBlob = pdfBase64ToBlob(url) // pdf就调用该方法,图片调用imgURLtoBlob()
const myUrl = URL.createObjectURL(myBlob) downloadFile(myUrl, name) } else { alert('文件不存在') } }

2、引用

import { downloadFileByBase64 } from '@/utils/downloadFile'

downloadFileByBase64(后端传的base64流, 文件名)

 

posted @ 2020-07-01 11:46  半忧夏  阅读(2544)  评论(0编辑  收藏  举报