【问题标题】:Sending list of images as response using Javascript使用 Javascript 发送图像列表作为响应
【发布时间】:2020-04-24 10:06:34
【问题描述】:

我正在制作一个获取图像名称列表的 API,然后它必须从 S3 存储桶中一个一个地下载它们,然后将它们全部作为响应发送。

问题是我的图片正在上传,但似乎当我将它们作为base64 放入列表中,然后尝试发送列表时,列表就空了。

const getImagesById = async (req, res) => {
  const { id } = req.params;
  const imagesSet = new Map();

  try {
    const documentFromDB = await document.findOne({ id });

    documentFromDB.devices.forEach((device) => {
      const images = new Set();
      device.images.forEach(item => images.add(downloadFromS3(item)))
      imagesSet.set(device.name, JSON.stringify(mapToObj(images))) // tried adding just images also but neither works
    });
    res.status(200).json(JSON.stringify(mapToObj(imagesSet)));
  } catch (e) {
    console.log(`An error occurred : ${e.message}`);
    res.status(500)
      .send(e.message);
  }
};

function mapToObj(inputMap) {
  let obj = {};
  inputMap.forEach(function(value, key){
    obj[key] = value
  });
  return obj;
}

这就是我从 S3 获取图像的方式:

const downloadFromS3 = async (imageName) => {
  try {
    const image = await S3Utils.downloadFile(BUCKET_NAME, imageName);

    if (image.stack) {
      return null;
    }

    const imageBase64 = image.Body.toString('base64');
    return imageBase64;
  } catch (e) {
    console.log(`An error occurred while downloading : ${e.message}`);
    throw e;
  }
};

这是我目前得到的回应:

"{\"{ name: 'Martin'}\":\"{\\\"[object Promise]\\\":{}}\"}"

我要做的是获取一些设备名称,将它们映射到 Map 作为键,值作为 base64 图像列表,然后将其全部发送到 UI 以显示带有名称的图像。

我在这里做错了什么?

【问题讨论】:

  • 你能登录console.log(JSON.stringify(mapToObj(imagesSet)))吗?

标签: javascript node.js image base64 response


【解决方案1】:

您只需要在调用downloadFromS3函数之前添加await,从而改变上述所有函数。

const getImagesById = async (req, res) => {
  const { id } = req.params;
  const imagesSet = new Map();

  try {
    const documentFromDB = await document.findOne({ id });

    await Promise.all(documentFromDB.devices.map(async (device) => {
      const images = new Set();
      await Promise.all(device.images.map(async item => images.add(await downloadFromS3(item))))
      imagesSet.set(device.name, JSON.stringify(mapToObj(images))) // tried adding just images also but neither works
    }));
    res.status(200).json(JSON.stringify(mapToObj(imagesSet)));
  } catch (e) {
    console.log(`An error occurred : ${e.message}`);
    res.status(500)
      .send(e.message);
  }
};

function mapToObj(inputMap) {
  let obj = {};
  inputMap.forEach(function(value, key){
    obj[key] = value
  });
  return obj;
}

【讨论】:

  • 我现在似乎得到了一些真实的数据。谢谢你的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
  • 1970-01-01
  • 2013-07-24
  • 2013-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多