首页 > 解决方案 > 如果没有上传图像,如何将默认图像放入 multer?

问题描述

我正在尝试设置 multer,但图像存在一些问题,就目前而言,当我不上传任何图像时,服务器会给我一个错误,不允许我继续。我希望即使未上传图像,仍将值存储在数据库中。

这是我配置 multer 的地方:

    const express = require('express');
    const router = express.Router();
    const multer  = require('multer');
    
    const Clients = require('../models/clients.js')
    
    const storage = multer.diskStorage({
      destination: (req, file, callback) => {
        callback(null, "../emaildragger/public/uploads")
      },
      filename: (req, file, callback) => {
        callback(null, file.originalname)
      }
    })
    
    const upload = multer({storage: storage})
    
    router.route('/').get((req, res) => {
        Clients.find()
        .then(client => res.json(client))
        .catch(err => res.status(400).json('Error:' + err))
    })
    
    router.route('/:id').get((req, res) => {
      Clients.findById(req.params.id)
      .then(client => res.json(client))
      .catch(err => res.status(400).json("Error" + err))
    })
    
    router.route('/add').post(upload.single("image"), (req, res) => {
      
        const newClient = new Clients({
          image: req.file.originalname,
          firstName: req.body.firstName,
          lastName: req.body.lastName,
          weight: req.body.weight,
          BMI: req.body.BMI
        })
    
        newClient.save()
        .then (() => res.json(newClient))
        .catch(err => res.status(400).json('error' + err))
    })
    
    module.exports = router

这是我的模型:

    var mongoose = require('mongoose');
    
    var Schema = mongoose.Schema;
    
    var clientsSchema = new Schema(
      {
        image: 
          { type: String, required: false, default: 'Screenshot_293.png'},
        firstName: { type: String, required: true },
        lastName: { type: String, required: true },
        weight: { type: String, required: false },
        BMI: { type: String, required: false }
      }
    );
    
    
    const Clients = mongoose.model("clients", clientsSchema)
    
    
    module.exports = Clients

标签: javascriptnode.jsreactjsmongoosemulter

解决方案


错误出现在您的服务器中,因为您添加Multer了一个中间件,稍后在您的控制器中您尝试访问originalname上传的文件。如果您没有发送图像,则Multer不会解析和上传,文件将不存在。在这种情况下,您将尝试访问originalname不存在的东西的属性,因此您的服务器将抛出错误。

尝试像这样更改您的代码:

router.route('/add').post(upload.single("image"), (req, res) => {

   let client = {
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      weight: req.body.weight,
      BMI: req.body.BMI
   }  
   if(req.file && req.file.originalname) client.image = req.file.originalname;
   
   const newClient = new Clients(client)

   newClient.save()
   .then (() => res.json(newClient))
   .catch(err => res.status(400).json('error' + err))
})

推荐阅读