当前位置:   article > 正文

JS 文件base64、File、Blob、ArrayBuffer互转_js file转arraybuffer

js file转arraybuffer

二进制互转

1.file对象转base64

 let reader = new FileReader();
 reader.readAsDataURL(file[0])
 console.log(reader.result)
  • 1
  • 2
  • 3

2.base64 转成blob 上传

function dataURItoBlob(dataURI) {  
    var byteString = atob(dataURI.split(',')[1]);  
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];  
    var ab = new ArrayBuffer(byteString.length);  
    var ia = new Uint8Array(ab);  
    for (var i = 0; i < byteString.length; i++) {  
        ia[i] = byteString.charCodeAt(i);  
    }  
    return new Blob([ab], {type: mimeString});  
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3.blob 转成ArrayBuffer

let blob = new Blob([1,2,3,4])
let reader = new FileReader();
reader.onload = function(result) {
    console.log(result);
}
reader.readAsArrayBuffer(blob);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4.buffer 转成blob

let blob = new Blob([buffer])
  • 1

5.base64 转 file

const base64ConvertFile = function (urlData, filename) { // 64转file
  if (typeof urlData != 'string') {
    this.$toast("urlData不是字符串")
    return;
  }
  var arr = urlData.split(',')
  var type = arr[0].match(/:(.*?);/)[1]
  var fileExt = type.split('/')[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], 'filename.' + fileExt, {
    type: type
  });
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

6.blob转成file

let file = new window.File([blob], filename, filetype)
  • 1

7.file转blob

let blob = new Blob(['这里是要转换的字符串或者图片等'], {type: "text/plain;charset=utf-8"})
let reader = new  FileReader()
reader.readAsDataURL(blob)
reader.onload = (e)=> {
    console.log('e就是读取文件返回的对象')
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

8.blob转成text文本字符

async() => {
	return await (new Response(blob).text())
}
  • 1
  • 2
  • 3
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/145187
推荐阅读
相关标签
  

闽ICP备14008679号