我正在尝试访问一个接收了八位字节流作为参数的API。 为此,我想先将base64字符串转换为八位字节流。 在javascript中,我使用默认的Blob类型实现了it。 但是在NodeJS中,我无法使其成为API会消耗的完美格式。
我也尝试将其转换为Buffer和ArrayBuffers,但没有用。 我也尝试过cross-blob库,但是仍然无法像在JavaScript中那样将其转换为确切的格式。
答案 0 :(得分:0)
尝试一下:
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);
});
结果:
希望有帮助。