ArrayBuffer to base64 encoded string

前端 未结 12 1325
渐次进展
渐次进展 2020-11-22 07:16

I need an efficient (read native) way to convert an ArrayBuffer to a base64 string which needs to be used on a multipart post.

12条回答
  •  旧时难觅i
    2020-11-22 08:21

    This works fine for me:

    var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(arrayBuffer)));
    

    In ES6, the syntax is a little simpler:

    let base64String = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));
    

    As pointed out in the comments, this method may result in a runtime error in some browsers when the ArrayBuffer is large. The exact size limit is implementation dependent in any case.

提交回复
热议问题