base64ToFile.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const util = {
  2. // 创建一个a标签,并做下载点击事件
  3. downloadFile: function (blob, fileName) {
  4. if (window.navigator.msSaveOrOpenBlob) {
  5. // 兼容ie11
  6. try {
  7. window.navigator.msSaveOrOpenBlob(blob, fileName)
  8. } catch (e) {
  9. console.log(e)
  10. }
  11. return
  12. }
  13. const link = document.createElement('a')
  14. link.href = window.URL.createObjectURL(blob)
  15. link.download = fileName
  16. // 此写法兼容可火狐浏览器
  17. document.body.appendChild(link)
  18. const evt = document.createEvent('MouseEvents')
  19. evt.initEvent('click', false, false)
  20. link.dispatchEvent(evt)
  21. document.body.removeChild(link)
  22. },
  23. // 将Base64文件转为 Blob
  24. buildBlobByByte: function (data) {
  25. const raw = window.atob(data)
  26. const rawLength = raw.length
  27. const uInt8Array = new Uint8Array(rawLength)
  28. for (let i = 0; i < rawLength; ++i) {
  29. uInt8Array[i] = raw.charCodeAt(i)
  30. }
  31. return new Blob([uInt8Array])
  32. },
  33. // 二进制数组 生成文件
  34. downloadFileByByte: function (data, fileName) {
  35. const blob = this.buildBlobByByte(data)
  36. this.downloadFile(blob, fileName)
  37. }
  38. }
  39. export default util