2021-12-14 文件转换Base64, Base64转文件流

加载文件转Base64:

function blobToBase64(blob) {
 return new Promise((resolve, _) => {
 const reader = new FileReader()
 reader.onloadend = () => resolve(reader.result)
 reader.readAsDataURL(blob)
 });
}

fetch('https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png')
  .then(res => res.blob())
  .then(async (res) => {
    console.log(await blobToBase64(res))
  })

Base64转文件流:

base64ToFile (xmlBase64) {
  let ctl = this.$refs.myWriterControl
  const bstr = atob(xmlBase64)
  et n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], 'xmlBase64', { type: 'text/xml' })
},

文件转流Base64:

var reader = new FileReader()
reader.readAsDataURL(this.files[0])
reader.onload = function(){
    console.log(reader.result)
};

Base64转文件并下载:

function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
}
 
function downloadFile(url,name='file'){
    var a = document.createElement("a")
    a.setAttribute("href",url)
    a.setAttribute("download",name)
    a.setAttribute("target","_blank")
    let clickEvent = document.createEvent("MouseEvents")
    clickEvent.initEvent("click", true, true)
    a.dispatchEvent(clickEvent)
}
 
function downloadFileByBase64(base64,name){
    var myBlob = dataURLtoBlob(base64)
    var myUrl = URL.createObjectURL(myBlob)
    downloadFile(myUrl,name)
}

你可能感兴趣的:(2021-12-14 文件转换Base64, Base64转文件流)