【问题标题】:Multer req.file.path "Cannot read property 'path' of undefined"Multer req.file.path “无法读取未定义的属性‘路径’”
【发布时间】:2018-07-22 03:23:45
【问题描述】:

我是 node.js 的新手,并尝试构建一个具有文件上传功能的简单 REST Api。对于文件上传,我使用来自 npm 的 multer 并使用 POSTMAN 发送发布请求。但是当我尝试使用multer 上传文件时,我收到了这个错误:

{
    "error": {
        "message": "Cannot read property 'path' of undefined"
    }
}

这是我的 API 代码

product.js

import express from 'express';
import mongoose from 'mongoose';
import Product from '../models/product.model';
import multer from 'multer';
import multipart from 'connect-multiparty';

const router = express.Router();

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './uploads');
    },
    filename: (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, false);
    } else {
        cb(new Error('Only .jpeg or .png files are accepted'), true);   
    }
};

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 5
    },
    fileFilter: fileFilter
});

router.post('/', upload.single('productImage'), (req, res, next) => {
    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({
            message: 'Created product successfully',
            createdProduct: {
                name: result.name,
                price: result.price,
                _id: result._id,
                request: {
                    type: 'GET',
                    url: `http://localhost:3000/products/${result._id}`
                }
            }
        });
    }).catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
});

这是模型

product.model.js

import mongoose from 'mongoose';

const productSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {type: String, required: true},
    price: {type: Number, required: true},
    productImage: { type: String, required: false }
});

module.exports = mongoose.model('Product', productSchema);

即使我使用connect-multipart 中间件来解决问题,但后来我得到了其他错误:

{
    "error": {
        "message": "stream ended unexpectedly"
    }
}

这是使用multipart时的代码

router.post('/', upload.single('productImage'), multipart(), (req, res, next) => {
    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({
            message: 'Created product successfully',
            createdProduct: {
                name: result.name,
                price: result.price,
                _id: result._id,
                request: {
                    type: 'GET',
                    url: `http://localhost:3000/products/${result._id}`
                }
            }
        });
    }).catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
});

我认为POSTMAN 没有问题。

现在谁能帮我解决这个问题。不解决问题就继续前进对我来说真的是个大问题......

提前致谢。

【问题讨论】:

    标签: javascript node.js express postman multer


    【解决方案1】:

    我认为问题在于您的回电被颠倒了。如果文件是 jpeg 或 png,您将需要 (null,true)。见下文:

    const fileFilter = (req, file, cb) => {
        // reject a file
        if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
            cb(null, true);
        } else {
            cb(new Error('Only .jpeg or .png files are accepted'), false);   
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 2021-03-24
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 2015-11-22
      • 2014-08-16
      相关资源
      最近更新 更多