javascript - 如果没有上传图像,如何将默认图像放入 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
解决方案
错误出现在您的服务器中,因为您添加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))
})
推荐阅读
- javascript - 为什么两种方式 Swiper JS 控件不起作用?
- html - 导航栏没有出现在永久链接 Jekyll 网站上
- python-3.x - 没有主键的Django模型中的“更新”而不是“保存”
- r - R:随机选择女性或男性来估算 NA
- python - 正则表达式模式打印数字的特定实例
- python - 无效的数字参数“/Wsign-compare”:无法在 Windows 上安装 pip 包或构建相应的库
- c# - 释放键后如何缩小我的角色
- node.js - 如何检查图像文件是否真的包含在expressjs的请求中
- kubernetes - kube-controller-manager 和 kube-scheduler leaderelection 丢失 Crashloopback
- c++ - c++中fgetc(stdin)使用数据库数据时如何避免二阶sql注入攻击