使用 Multer Express Nodejs 获取图像路径

Get image path with Multer Express Nodejs

我正在使用 Multer 保存图像,但我需要获取图像的路径才能将其保存到 MongoDB。我正在尝试使用 req.file 获取路径,但它总是在控制台上告诉我它未定义。

这是我的路线:

import { Router } from 'express';
import { check, validationResult } from 'express-validator';

const multer  = require('multer');

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, 'uploads/products')
    },
    filename: function (req, file, cb) {
      cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname)
    }
  });

const fileFilter = (req, file, cb) => {
    // reject a file

    if (file.mimetype === 'image/jpeg' ||file.mimetype === 'image/png') {
        cb(null, true);                
    } else {
        cb(null, false); 
        //cb(new Error('I don\'t have a clue!'))       
    }
}
  
const upload = multer(
    { storage: storage, 
    limits:{
        fileSize: 1024 * 1024 
    },
    fileFilter: fileFilter
});

let router = Router();

router.post('/', upload.single('img'),
    newProduct
);

在新的 Product 控制器中,我试图读取 req.file 但控制台告诉我它未定义:

控制器:


import { Product } from '../models'

let newProduct = async (req, res = response ) => {

     console.log('file ' + req.file); //UNDEFINED

    try {

        let { status, user, ...body } = req.body;


        let productDB = await Product.findOne ( { 'name': body.name } );
    
        if (productDB) {
    
            return res.status(400).json({
            
                msg:`El producto ${ productDB.name } ya existe`
            })
        }
    
        let data = { 
            ...body, 
            name: body.name, 
            user: req.user._id 
        }
    
        let product = new Product( data );
    
        await product.save();
    
        res.status(200).json( product );

    } catch (error) {

        return res.status(400).json({     
            error
        });   
    }
}


控制台:

感谢您的帮助。

您可以尝试在文件名中执行此操作:

filename: function (req, file, cb) {
  req.imageName = new Date().toISOString().replace(/:/g, '-') + file.originalname
  cb(null, req.imageName)
}

然后他们的:

console.log('file ' + req.file); //UNDEFINED
//you can get imageName instead
console.log('imageName',req.imageName)
//if you want url to store in database you can do this 
//supposing your have images directory in root of your node server
const url = `${req.protocol}://${req.get('host')}/images/${req.body.image}`