typescript 在类型脚本中将字符串/文本转换为字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38607676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert string/Text to byte array in type script
提问by sachin kulkarni
I am Currently working on task to download file (PDF/excel/text) using secure API in my system in angular 2 (beta) version.
我目前正在处理使用 angular 2(测试版)系统中的安全 API 下载文件(PDF/excel/文本)的任务。
I have used post API with authentication header and trying to create blob using data bytes received.
我使用带有身份验证标头的 post API 并尝试使用接收到的数据字节创建 blob。
I have tried using following code
我尝试使用以下代码
return this.http.get(url, { headers: this.headers}).map( response => response.blob())
But, i got the error that blob method is not implemented in angular 2 HTTP.
但是,我得到的错误是 blob 方法没有在 angular 2 HTTP 中实现。
so i am trying following code where i need to convert string to byte array.
所以我正在尝试以下代码,我需要将字符串转换为字节数组。
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);
}
);
here i am facing some issue with the bytes array. Byte array is not same as the one sent by the API.
在这里,我遇到了字节数组的一些问题。字节数组与 API 发送的数组不同。
Need help in either converting string to byte array or using blob in angular 2 HTTP get request.
在将字符串转换为字节数组或在 angular 2 HTTP get 请求中使用 blob 时需要帮助。
回答by Varit J Patel
Probably, The below npm package can help you convert it into ByteArray.
可能,下面的 npm 包可以帮助您将其转换为 ByteArray。
https://www.npmjs.com/package/xdata
https://www.npmjs.com/package/xdata
Hope it helps you!
希望对你有帮助!
Cheers!
干杯!