bolb、bloburl、file、base64间的转换

bloburl格式:

blob:http://localhost:8080/c69fbb0e-b234-4926-bb3e-aa6103a169fa

blob格式:

Blob {size: 272260, type: ‘application/pdf’}size: 272260type: “application/pdf”[[Prototype]]: Blob

file格式:

base64格式:

data:application/pdf;base64,JVBERi0xLjMKJbrfrOAKMyAwIG9iag…

1.bloburl转换为file

httpRequest(src) {
   let that = this
   return new Promise((resolve, reject) => {
   let xhr = new XMLHttpRequest()
   xhr.open('GET', src, true)
   xhr.responseType = 'blob'
   xhr.onload = function (e) {
     if (this.status == 200) {
       let myBlob = this.response
       let files = new window.File([myBlob], that.objData.prj_no + '.pdf', { type: myBlob.type }) // myBlob.type 自定义文件名
       resolve(files)
    } else {
         reject(false)
    }
  }
    xhr.send()
 })
}

2.file转换为base64

getBase64(file) {
   return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = (error) => reject(error)
    })
}

3.base64转换为file

base64ImgtoFile(dataurl, filename = 'file') {
    const arr = dataurl.split(',')
    const mime = arr[0].match(/:(.*?);/)[1]
    const suffix = mime.split('/')[1]
    const bstr = atob(arr[1])
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
         u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], `${filename}.${suffix}`, {
       type: mime,
    })
}

4.base64转换为blob

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 })
}

5.blob转换为base64

blobToDataURL(blob, callback) {
  let a = new FileReader()
  a.onload = function (e) {
     callback(e.target.result)
  }
  a.readAsDataURL(blob)
},

你可能感兴趣的:(javascript)