简体   繁体   中英

How to upload an image file(jpg, png, etc... and store it in MongoDB?

Whenever I have to upload an image I Upload it on imgbb and then paste the link as text. Thanks in Advance.

I need a proper way to upload an image and pro tips for handling files like images, pdf, video etc.

I have used a package called multer to handle this. Here is a basic tutorial of its functionality using React.

Here is a snippet of code where I have actually used it, just so you can have a little context:

const express = require('express')
const multerRoutes = express.Router()
const multer = require('multer')
const path = require('path')

const Client = require("../../models/clientSchema");

//specify where to store incoming files
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, "./public/assets/img/users"))
    },
    filename: function (req, file, cb) {
        cb(null, new Date().toISOString().replace(/[\/\\:]/g, "_") + "_" + file.originalname)
    }
})

//specify file filters -- only allow img extentions
const fileFilter = (req, file, cb) => {
    if (file.mimetype === 'image/jpeg' ||
        file.mimetype === 'image/png' ||
        file.mimetype === 'image/jpg'
    ) {
        cb(null, true);
    } else {
        console.error("Wrong File Format")
        cb(null, false);
    }
}

//initialize multer
const upload = multer({ storage: storage, fileFilter: fileFilter });


//uploads image -- can upload array of images if you change parameters
multerRoutes.post('/order-profile', upload.single('img'), function (req, res, err) {
    try {
        if (err instanceof multer.MulterError) {
            console.log(err)
        } else if (err) {
            console.log(err)
        }

    //create and save new Client
    const client = new Client({
      _id: new mongoose.Types.ObjectId(),
      name: req.body.name,
      img: url + "/public/assets/img/users" + req.file.filename,
    });
    client
      .save()
      .then((result) => {
        res.status(201).json({
          message: "Client registered successfully!",
          clientCreated: {
            _id: result._id,
            img: result.img, 
          },
        });
      })
      .catch((err) => {
        console.log(err),
          res.status(500).json({
            error: err,
          });
      });

        res.render('confirm')
    } catch (err) {
        console.log("Error loading file")
        console.error(err)
        res.render('errorPage')
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM