ArrayBuffer to base64 encoded string

前端 未结 12 1477
渐次进展
渐次进展 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条回答
  •  滥情空心
    2020-11-22 08:05

    There is another asynchronous way use Blob and FileReader.

    I didn't test the performance. But it is a different way of thinking.

    function arrayBufferToBase64( buffer, callback ) {
        var blob = new Blob([buffer],{type:'application/octet-binary'});
        var reader = new FileReader();
        reader.onload = function(evt){
            var dataurl = evt.target.result;
            callback(dataurl.substr(dataurl.indexOf(',')+1));
        };
        reader.readAsDataURL(blob);
    }
    
    //example:
    var buf = new Uint8Array([11,22,33]);
    arrayBufferToBase64(buf, console.log.bind(console)); //"CxYh"
    

提交回复
热议问题