You need to enable JavaScript to run this app. 如何将API返回的PNG格式图片存储到MongoDB中
优惠活动
大模型
产品
解决方案
定价
更多

如何将API返回的PNG格式图片存储到MongoDB中

实现步骤

核心注意点是调用二维码接口时必须指定响应类型为二进制格式,否则返回的二进制数据会被默认当做UTF-8字符串解析,就会出现你看到的乱码,无法转换为正确的Buffer存储。以下是Node.js环境下的完整实现:

1. 请求接口时配置响应类型

根据你用的请求工具不同,对应配置如下:

axios 实现示例

const axios = require('axios');
const mongoose = require('mongoose');

// 对应你给出的Schema定义Model
const QrModel = mongoose.model('QrCode', new mongoose.Schema({
  qrCode: { 
    data: Buffer, 
    contentType: String 
  }
}));

async function saveQrToMongo() {
  try {
    const qrApiUrl = 'http://api.qrserver.com/v1/create-qr-code/?data=https://www.google.com&size=100x100';
    // 关键配置:指定响应类型为arraybuffer,拿到原始二进制数据
    const response = await axios.get(qrApiUrl, {
      responseType: 'arraybuffer'
    });

    // 构造存储数据
    const qrRecord = new QrModel({
      qrCode: {
        data: response.data, // 拿到的arraybuffer可直接匹配Schema的Buffer类型
        contentType: 'image/png'
      }
    });

    // 写入MongoDB
    await qrRecord.save();
    console.log('二维码存储成功');
  } catch (error) {
    console.error('存储失败:', error);
  }
}

node-fetch 实现示例

const fetch = require('node-fetch');

async function saveQrToMongo() {
  try {
    const qrApiUrl = 'http://api.qrserver.com/v1/create-qr-code/?data=https://www.google.com&size=100x100';
    const response = await fetch(qrApiUrl);
    // 把响应转为ArrayBuffer再封装为Buffer
    const imgBuffer = Buffer.from(await response.arrayBuffer());

    const qrRecord = new QrModel({
      qrCode: {
        data: imgBuffer,
        contentType: 'image/png'
      }
    });
    await qrRecord.save();
    console.log('二维码存储成功');
  } catch (error) {
    console.error('存储失败:', error);
  }
}

附加:读取存储的二维码返回前端的方法

后续需要返回图片给前端时,只要设置正确的响应头即可:

// 基于express的示例接口
app.get('/get-qr/:id', async (req, res) => {
  const qrRecord = await QrModel.findById(req.params.id);
  res.set('Content-Type', qrRecord.qrCode.contentType);
  res.send(qrRecord.qrCode.data);
})

内容的提问来源于stack exchange,提问作者Siddharth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 05:00:01