1

我从 HTTP 请求接收到以下二进制流:

HTTP 请求

Document.get({id: $scope.documentId}, function(stream){

});

角工厂

.factory('Document', ['$resource', 'DOCUMENTS_CONFIG',
    function($resource, DOCUMENTS_CONFIG) {
        return $resource(DOCUMENTS_CONFIG.DETAIL_URL, {}, {
            get: {
                method: 'GET', 
                params: {}, 
                url: DOCUMENTS_CONFIG.DETAIL_URL,
                isArray: false
            }
        });
    }
]);

回复

console.log(stream) 我需要将其转换为 Uint8Array。我试图将其转换为 bas64

// Convert Binary Stream To String
var dataString = JSON.stringify(stream);

// Convert to Base 64 Data
var base64Data = window.btoa(unescape(encodeURIComponent(dataString)));  

当我运行它时,我得到一个错误'格式错误的 uri 异常'。我也尝试过 window.btoa(dataString) 但我得到“无法在 'Window' 上执行 'btoa':要编码的字符串包含 Latin1 范围之外的字符。”

如何将其转换为 Uint8Array?

4

1 回答 1

3

所以你有一个二进制流(我假设的值是从某种字节数组发送的,0-255)。在window.btoa(...)将其转换为Uint8Array.

You simple need to iterate through the Object's indexes (which are stored in key's increasing in value from 0) and set the value of the Uint8Array, grabbing the character code at each index, and setting the Uin8Array cell at that index to the value.

You need to know the number of Keys, this is achievable via Object.keys(stream).length. Then, we iterate our key value (i) and grab the charCode(0) at zero (because the value for each key is a 1-character string) .

var bytes = Object.keys(stream).length;
var myArr = new Uint8Array(bytes)

for(var i = 0; i < bytes; i++){
    myArr[i] = stream[i].charCodeAt(0);
}

I updated your fiddle, you can in the console log how it is converting. I also truncated the string because I got tired of finding all the ' characters and trying to escape them and adding \n characters so it'd all be on one line.

于 2015-02-12T16:21:23.423 回答