将图片上传到服务器时的路径无效

时间:2018-06-10 11:09:01

标签: javascript node.js express

服务器与node.js + express,我需要上传img到server.I尝试在谷歌找到一些关于它的信息,发现multer.Now我想保存在DB只有我的images的路径。那我怎么做:< / p>

const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')
const multer = require('multer')

const storage = multer.diskStorage({
    destination: function (req,file,cb) {
        cb(null,'./uploads/')
    },
    filename: function(req,file,cb){
        cb(null,Date.now() + '-' + file.originalname)
    }
})
const fileFilter = (req,file,cb) => {
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
        cb(null, true)
    }else{
        cb(null,false)
    }
}

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

const Product = require('../models/products')


router.post('/',upload.single('productImage'), (req, res, next) => {
    console.log(file)
    const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price,
        productImage: req.file.path
    })
    product.save()
        .then((result) => {
            console.log(result)
            res.status(201).json({
                createdProduct: result
            })
        })
        .catch(err => {
            console.log(err)
            res.status(500).json({
                error: err
            })
        })
})

但我有错误:file is not defined。 我想我失败了productImage: req.file.path但我不知道如何解决这个问题。你能帮助我吗?

0 个答案:

没有答案