亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Base64編碼后將axios圖像流轉換為字符串?

Base64編碼后將axios圖像流轉換為字符串?

慕哥9229398 2022-06-05 09:47:35
到目前為止,我有這個:const Fs = require('fs')  const Path = require('path')  const Axios = require('axios')var {Base64Encode} = require('base64-stream');const url = 'https://unsplash.com/photos/AaEQmoufHLk/download?force=true'const response = await Axios({      url,      method: 'GET',      responseType: 'stream'    })response.data.pipe(new Base64Encode())這個base 64 對圖像進行編碼。我們怎樣才能把它變成一個字符串。我試過這樣的事情:  function streamToString (stream) {    const chunks = []    return new Promise((resolve, reject) => {      stream.on('data', chunk => chunks.push(chunk))      stream.on('error', reject)      stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))    })  }const result = await streamToString(response.data.pipe(new Base64Encode()))但它錯誤。想法?
查看完整描述

1 回答

?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

在您的示例中,您使用了Base64encode已經抽出字符串的模塊 - 這使得上面的示例失?。ǔ悄鞘且驗轫敿壍却?。您實際上不需要將塊轉換為字符串,因為它們已經是字符串,因此可以進行簡單的串聯。


事實上,僅使用 node.js 流,整個事情可能會簡單 10 倍:


const Axios = require('axios')

const {PassThrough} = require("stream");


const url = 'https://unsplash.com/photos/AaEQmoufHLk/download?force=true';


(async function() {

    const response = await Axios({

        url,

        method: 'GET',

        responseType: 'stream'

    });


    // we just pipe the data (the input carries it's own encoding)

    // to a PassThrough node stream that outputs `base64`.

    const chunks = response.data

        .pipe(new PassThrough({encoding:'base64'}));


    // then we use an async generator to read the chunks

    let str = '';

    for await (let chunk of chunks) {

        str += chunk;

    }


    // et voila! :)

    console.log(str);

})();


查看完整回答
反對 回復 2022-06-05
  • 1 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號