【问题标题】:How to convert FetchAPI parsed Blob Results to Base64如何将 Fetch API 解析 Blob 结果转换为 Base64
【发布时间】:2019-03-05 17:29:30
【问题描述】:

拥有这个从 API 端点获取图像的module.exports 文件。然后将 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 格式,有什么想法吗?

【问题讨论】:

  • data.toString('base64')?或者 data.buffer.toString('base64') - 我不熟悉 nodejs 中的 blob
  • @Nezir - 这不是 nodejs
  • 不过,它可能更像const data = await response.buffer(); console.log(data.toString('base64')) - 因为 Blob 缓冲区似乎很难获得

标签: javascript node.js image base64 blob


【解决方案1】:

查看 node-fetch,似乎无法获取 Blob 缓冲区,因此,最好的办法是执行以下操作

  1. 使用 response.buffer 代替 response.blob
  2. 使用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);
}; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-25
    • 2021-07-27
    • 2017-11-25
    • 2021-05-03
    • 2013-09-10
    • 2020-11-10
    • 2015-12-20
    • 2021-06-20
    相关资源
    最近更新 更多