【问题标题】:NodeJS convert base64 to octet-streamNodeJS 将 base64 转换为八位字节流
【发布时间】:2020-04-09 07:21:31
【问题描述】:

我正在尝试访问一个接收八位字节流作为参数的API。 为此,我想先将 base64 字符串转换为八位字节流。 在 javascript 中,我使用默认的 Blob 类型实现了it。 但在 NodeJS 中,我无法将其制作成 API 可以使用的完美格式。

我也尝试将其转换为 Buffer 和 ArrayBuffers,但没有用。 我也尝试过 cross-blob 库,但它仍然没有被转换为我在 javaScript 中的确切格式。

【问题讨论】:

  • 没有任何代码,我不清楚您所说的“流”是什么意思。但是,使用 Buffer API 在 nodejs 中将 base64 分块转换为二进制很容易。
  • 您好,我的回答对您有帮助吗?需要进一步的帮助吗?
  • 是的@StanleyGong,效果很好。

标签: javascript node.js blob buffer azure-cognitive-services


【解决方案1】:

试试这个:

const fetch = require("node-fetch")
const fs  = require('fs');


let subscriptionKey = '<your key here>';
let endpoint = '<endpoint url of your vision serice>';
let filePath = '<path of your file>';

//code below is what you are looking for 
const base64 =  fs.readFileSync(filePath, 'base64') 
const data = Buffer.from(base64, 'base64')

if (!subscriptionKey) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }

var uriBase = endpoint + "vision/v2.1/ocr";  //you define your API here , in this case I use ocr 

fetch(uriBase + "?" + {
    "language": "unk",
    "detectOrientation": "true",
},
{
method: 'POST',
headers: 
    {
    'Content-Type': 'application/octet-stream',
    'Ocp-Apim-Subscription-Key': subscriptionKey,
    },
body: data,    //post binary data directly, it applys to all post methods which data type is octet-stream in vision serice API 
}).then((response) => response.json()).then((data) =>
{
console.log(JSON.stringify(data, null, 2));
}).catch((error) =>
{
console.log(error);
});

结果:

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    相关资源
    最近更新 更多