簡體   English   中英

NodeJS 將 base64 轉換為八位字節流

[英]NodeJS convert base64 to octet-stream

我正在嘗試訪問一個接收八位字節流作為參數的API 為此,我想首先將 base64 字符串轉換為八位字節流。 在 javascript 中,我使用默認的 Blob 類型實現了 但是在 NodeJS 中,我無法使其成為 API 使用的完美格式。

我也嘗試將其轉換為 Buffer 和 ArrayBuffers,但沒有用。 我也嘗試過跨 blob庫,但它仍然沒有像我在 javaScript 中那樣被轉換為確切的格式。

嘗試這個 :

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);
});

結果 :

在此處輸入圖片說明

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM