11
file转base64
/**
 * 上传附件转base64
 * @param {File} file 文件流
 */
export const fileByBase64 = (file, callback) => {
  var reader = new FileReader();
  // 传入一个参数对象即可得到基于该参数对象的文本内容
  reader.readAsDataURL(file);
  reader.onload = function (e) {
    // target.result 该属性表示目标对象的DataURL
    console.log(e.target.result);
    callback(e.target.result)
  };
}
base64转file
export const base64ImgtoFile = (baseUrl, filename = 'file') => { 
  const arr = baseUrl.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
  })
}
base64转blob
/**
 * base64转Blob
 * @param {*} data 
 */
export const base64ByBlob = (base64, callback) => {
  var arr = base64.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  console.log(new Blob([u8arr], { type: mime }))
  callback(new Blob([u8arr], { type: mime }))
}
blob转url
var url = window.URL.createObjectURL(blob)
es6使用例子
fileByBase64(file, (base64) => {
    base64ByBlob(base64, (blob => {
      console.log(blob, 'blob')
      var url = window.URL.createObjectURL(blob)
      console.log(url, 'url')
    })
})

clipboard.png


Max迪丶先生
1.8k 声望64 粉丝