代码之家  ›  专栏  ›  技术社区  ›  Leo Messi

从中的二进制文件重新创建图像节点.js还有猫鼬

  •  0
  • Leo Messi  · 技术社区  · 4 年前

    我正在创建一个上传/下载图像功能节点.js. 到目前为止,有一个POST请求将图像保存为MongoDB中的二进制文件,还有一个GET请求将图像返回。但我不知道如何使用这个响应,它是一个数字数组,不知道如何转换它。

    图片.js const mongoose=require('mongoose');

    const ImageItem = new Schema({
      id: {
        type: String
      },
      value: {
        type: Buffer
      },
    });
    
    module.exports = Image = mongoose.model('image', ImageItem);
    

    后期图像 在数据库中创建一个条目:

    const image = require('../models/image');
    const user = require('../models/user');
    
    const multer = require('multer');
    const storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, './uploads/');
      },
      filename: function (req, file, cb) {
        cb(null, file.originalname + new Date().toISOString());
      },
    });
    
    
    const upload = multer({
      storage: storage,
    });
    
    module.exports = function (app) {
      app.post('/upload', upload.single('value'), (req, res, next) => {
        const newImage = new image({
          id: req.body.id,
          value: req.file.path,
        });
        newImage
          .save()
          .then((result) => {
            console.log(result);
            res.status(201).json({
              message: 'created succesfully',
            });
          })
          .catch((err) => {
            console.log(err);
            res.status(500).json({
              error: err,
            });
          });
      });
    };
    

    以及在DB中创建的条目:

    enter image description here

    const image=require('../models/image');

    module.exports = function (app) {
      app.get('/upload/:id', (req, res) => {
        console.log('req.body.id', req.params);
        image.find({ id: req.params.id }, function (err, results) {
          if (err) {
            res.send(`error: ${err}`);
          } else {
            res.send(results);
          }
        });
      });
    };
    

    在Postman中测试返回一个包含数字数组的JSON:

    [
        {
            "_id": "5ebd1c112892f4230d2d4ab4",
            "id": "email123@test.com",
            "value": {
                "type": "Buffer",
                "data": [
                    117,
                    112,
                    108,
                    111,
                    97,
                    100,
                    115,
                    47,
                    117,
                    115,
                    101,
                    114,
                    80,
                    105,
                    99,
                    116,
                    117,
                    114,
                    101,
                    46,
                    112,
                    110,
                    103,
                    50,
                    48,
                    50,
                    48,
                    45,
                    48,
                    53,
                    45,
                    49,
                    52,
                    84,
                    49,
                    48,
                    58,
                    50,
                    51,
                    58,
                    49,
                    51,
                    46,
                    57,
                    51,
                    52,
                    90
                ]
            },
            "__v": 0
        }
    ]
    

    如何使用这些数据获得实际图像?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Marcos Casagrande    4 年前

    Buffer 从那个阵列。

    const imageBuffer = Buffer.from(row.value.data); // [117, 112, 108...]
    

    在任何情况下检查你的 ImageItem 模式, row.value 将会是一个 缓冲器 .

    现在你需要做的就是设置正确的 content-type 缓冲器 而不是Mongoose模式,使用 res.send

    app.get('/upload/:id', (req, res) => {
        console.log('req.body.id', req.params);
        image.find({ id: req.params.id }, function (err, results) {
          if (err) {
            res.send(`error: ${err}`);
          } else {
            const [row] = results;
            res.header('Content-Type', 'image/png');
            res.send(row.value);
          }
        });
    });
    

    Content-Type 你可以用 file-type 缓冲器 .

    const { mime } = fileType(row.value)
    

    .findOne 而不是 .find


    现在有了另一个问题,存储的是文件路径,而不是所需的二进制图像。

    你发布的字节等于: uploads/userPicture.png2020-05-14T10:23:13.934Z"

    const data = new TextDecoder().decode(new Uint8Array([117,112,108,111,97,100,115,47,117,115,101,114,80,105,99,116,117,114,101,46,112,110,103,50,48,50,48,45,48,53,45,49,52,84,49,48,58,50,51,58,49,51,46,57,51,52]))
    
    console.log(data);

    const fs = require('fs').promises;
    // ....
    
    const newImage = new image({
          id: req.body.id,
          value: await fs.readFile(req.file.path)
    });