ArrayBuffer to base64 encoded string

前端 未结 12 1492
渐次进展
渐次进展 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:10

    You can derive a normal array from the ArrayBuffer by using Array.prototype.slice. Use a function like Array.prototype.map to convert bytes in to characters and join them together to forma string.

    function arrayBufferToBase64(ab){
    
        var dView = new Uint8Array(ab);   //Get a byte view        
    
        var arr = Array.prototype.slice.call(dView); //Create a normal array        
    
        var arr1 = arr.map(function(item){        
          return String.fromCharCode(item);    //Convert
        });
    
        return window.btoa(arr1.join(''));   //Form a string
    
    }
    

    This method is faster since there are no string concatenations running in it.

提交回复
热议问题