【问题标题】:nodejs: Retrieving base64 Images from Mongodb using Postmannodejs:使用 Postman 从 Mongodb 检索 base64 图像
【发布时间】:2020-11-02 18:21:06
【问题描述】:

寻求有关使用 multer 从 MongoDb 上传和检索图像的帮助。

我的前端是 ReactNative。(不确定是否需要,但只是为了确定。)

穆特

问题:在查看并遵循教程后,我能够将我的路径编码为 base64 并将其上传到我的数据库,但现在我很困惑如何从我的数据库中检索文件。我看到了一些关于从 base64 解码它的教程,但我不太明白如何检索图像并在邮递员中显示它。 (我试着寻找,但没有找到任何能给我答案的东西。如果这是一个重复的问题,我很抱歉。如果你能指出我的方向或给我一些建议,我会非常感激。)

**POST**
route.post("/sad", upload.single("image"), (req, res, next) => {
  console.log(req.file);

  const img = fs.readFileSync(req.file.path);
  const img_enc = img.toString('base64');
  const obj = {
    usrImage: {
      data: new Buffer.from(img_enc, 'base64'),
      contentType: "image/jpg",
    },
  };
  console.log(obj);
  const newAccout = new account(obj);
  newAccout.save();
});


**RETRIEVE**
route.get('/sad',(req,res)=>{
     img.find({}).then((img)=>{
       res.json(img)      
//How do decode my buffer to show an image in Postman?
})
}
)

我正在尝试创建一个保存用户名、密码和图像的用户配置文件。如果您可以帮助保存图像,然后从我的帐户集合中检索它。

【问题讨论】:

  • 只是一个疯狂的猜测:如果你想显示它,我认为你不应该用 JSON 对象包装 IMG 数据。您应该传递一些内容类型标题(图像/jpg)并将响应选项卡更改为在邮递员中预览。
  • 感谢您的回复。您能否详细说明如何传递内容类型标头?
  • nodejs.org/api/http.html#http_response_setheader_name_value 这里是文档中对应的地方。内容类型标头用于告诉客户端如何呈现数据。

标签: node.js mongodb express multer


【解决方案1】:

嘿,我建议您开始使用第 3 方进行文件上传,例如 cloudinary,这是管理文件(即图像或视频)的非常好的方法......

我对 multer 不太熟悉,但我可以给出一个快速的代码示例,使用 Formidable 与 multer 的作用相同

在开始之前,您需要在 cloudinary.com 上创建一个帐户(不用担心它是免费的)

下面的代码是您如何处理文件上传

const Formidable = require("formidable"); //Meant for body parsing
const cloudinary = require("cloudinary").v2; // file uploader

//This below is your connection/configuration to get access to your cloudinary account so cloud_name, api_key and api_secret you'll get in your home dashboard(Cloudinary)

cloudinary.config({
  cloud_name: process.env.CLOUD_NAME,
  api_key: process.env.API_KEY,
  api_secret: process.env.API_SECRET,
});

router.post('/api/file-upload', (req, res)=>{
    const form = new Formidable.InconmingForm();
    form.parse(req, (error, fields, files)=>{
        const {file} = files

        cloudinary.uploader.upload(file.path, {folder:"/"}, (err, res)=>{
        const file_url = res.secure_url //This would be the url for your file given back by cloudinary
        })
    })
})

此脚本应该上传您的文件,file_url 将包含您上传的文件的 url,其中包含 ssl 然后您现在可以继续保存到 mongoDB

NodeJS 的 Cloudinary 文档 https://cloudinary.com/documentation/node_integration

清晰易懂的文档

无耻的塞

如果你迷路了,你可以在 YouTube 上查看我用 cloudinary 处理文件上传的视频,然后保存返回给 mongoDB 的 url

https://youtu.be/mlu-tbr2uUk

【讨论】:

  • 感谢您的回复。抱歉,这不是我想要的,但我确实看过你的视频,如果我需要使用 cloudinary,我会转播。
【解决方案2】:

先调用api找一个

您将需要 fs 模块来完成以下查询

const fs = require('fs');

let data = await db.user.findOne({
    where: {
        id = req.body.id
    }
})
                         //   _________________ base 64 string data from findone query data
                         //  |
let buff = new Buffer(data.image, 'base64');

let name = name.jpeg
let path = `tmp/${name}`; // <--- destination and file name you want to give to your file

fs.writeFileSync(path, buff);// < --this will write file to given path

fs.readFile(path, function (err, content) {//  <------to send file in postman response
    if (err) {
        res.writeHead(400)
        console.log(err);
        res.end("No such image");
    } else {
         //specify the content type in the response will be an image
        res.writeHead(200);
        res.end(content);
    }
});

fs.unlink(path, (err) => { //  <-----to delete file from tmp directory
    if (err) {
        console.log(err)
    }
})

【讨论】:

    【解决方案3】:

    试试这个并切换到邮递员的预览标签。 我没试过,但也许有帮助。

    route.get('/sad',(req,res)=>{
         img.find({}).then((img)=>{
              res.setHeader('contentType','image/jpg').send(img)      
          })
    })
    

    【讨论】:

    • 我试过这种方式,我只是在预览选项卡中检索数据。它不响应图像。
    • 也许发送img.data。我真的在这里猜。 “检索数据”是什么意思?
    • 当我使用您的代码 sn-p 从我的 Db 集合中获取图像文件时,它会响应:` {"usrImage":{"data":{"type":"Buffer"," data":[255,216,255,224,0,16,74,70,73,70, ....` 它还在预览选项卡中显示所述数据而不是图像。
    • 我认为您必须像在 post 函数中那样读取缓冲区。我还没有做过那样的事情,所以也许看看如何使用 Buffer.from 并以你保存在那里的方式从你的数据库中加载数据。
    • 抱歉,我好像还是迷路了。您知道将图像上传到 MongoDb 并检索所述图像的任何好的教程吗?
    猜你喜欢
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多