拥有此 module.exports
文件,用于从 API 端点获取图像。然后,API 结果被解析为 blob。解析 Blob 对象后如下所示:
Blob {
[Symbol(type)]: 'image/jpeg',
[Symbol(buffer)]:
<Buffer ff d8 ff db 00 43 00 08 06 06 07 06 05 08 07 07 07 09 09 08 0a 0c 14
0d 0c 0b 0b 0c 19 12 13 0f 14 1d 1a 1f 1e 1d 1a 1c 1c 20 24 2e 27 20 22 2c 23 1c
... > }
这是代码:
// Pre Configuration
const fetch = require('node-fetch')
module.exports = async (req, res, photoKey) => {
let photoUrl = null
const apiURL = "https://media.heartenly.com/stg/CACHE/sc_thumb"
const requestURL = `${apiURL}/${photoKey}`
const response = await fetch(requestURL)
const data = await response.blob()
console.log(data)
}
现在我想做的是返回返回的 blob 的 base64 URL 格式,有什么想法吗?
最佳答案
查看 Node 获取,看起来不可能获取 Blob 缓冲区,因此,最好的选择是执行以下操作
- 使用response.buffer而不是response.blob
- 使用toString('base64')获取base64格式的数据
换句话说:
const fetch = require('node-fetch');
module.exports = async (req, res, photoKey) => {
let photoUrl = null;
const apiURL = "https://media.heartenly.com/stg/CACHE/sc_thumb";
const requestURL = `${apiURL}/${photoKey}`;
const response = await fetch(requestURL);
const data = await response.buffer()
const b64 = data.toString('base64');
console.log(b64);
};
关于javascript - 如何将 Fetch API 解析 Blob 结果转换为 Base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52576973/