gpt4 book ai didi

javascript - axios图片流Base64编码后转成字符串?

转载 作者:行者123 更新时间:2023-12-05 02:08:27 25 4
gpt4 key购买 nike

到目前为止我有这个:

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()))

但是它出错了。想法?

最佳答案

在您的示例中,您使用了已经输出字符串的 Base64encode 模块 - 这使得上面的示例失败(除非那是因为顶层等待)。您实际上不需要将 block 转换为字符串,因为它们已经是字符串,所以简单的连接就可以了。

事实上,仅使用 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);
})();

关于javascript - axios图片流Base64编码后转成字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60894483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com