在字符型脚本中将字符串/文本转换为字节数组

问题描述:

我目前正在使用我的系统在角度2(测试版)版本中使用安全API下载文件(PDF/excel/text)的任务。在字符型脚本中将字符串/文本转换为字节数组

我已经使用带验证头的post API,并尝试使用接收到的数据字节创建blob。

我已经使用以下代码

return this.http.get(url, { headers: this.headers}).map(response => response.blob()) 

试图但是,我得到了错误该斑点方法没有角2 HTTP实现。

所以我想下面的代码,我需要将字符串转换为字节数组。

return this.http.get(Configuration.API_URL + url, { headers: this.headers }).map(
      response => { 
       var bytes = []; 

       var utf8 = encodeURIComponent(response.text()); 
       for (var i = 0; i < utf8.length; i++) { 
        bytes.push(utf8.charCodeAt(i)); 
       }  
       var data = new Blob([bytes], { type: 'application/pdf' }); 
       var fileURL = URL.createObjectURL(data); 
       window.open(fileURL); 
      } 
     ); 

这里我正在面对字节数组的一些问题。字节数组与API发送的字节数组不同。

在将字符串转换为字节数组或在角度为2的HTTP请求中使用blob方面需要帮助。

+0

是的,blob()即将推出。同时,请检查此:http://stackoverflow.com/questions/35368633/angular-2-download-pdf-from-api-and-display-it-in-view – mico

+0

Thankyou mico 此xhr答案帮助我 –

+0

字节数组之间有什么区别?所有元素还是只有页眉/页脚? –

也许,下面的npm包可以帮助您将其转换为ByteArray。

https://www.npmjs.com/package/xdata

希望它可以帮助你!

干杯!