Multer req.file.path未定义

时间:2018-02-11 10:26:47

标签: javascript node.js express postman multer

抱歉这个简单的问题。我只是node.js的新手,并尝试用express表达RESTapi。对于文件上传,我正在使用来自npm的multer。一切都很好。但是当我尝试使用 req.file.path 在post方法中访问multer属性时,它会抛出此消息:

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

我也尝试在multer中提供其他属性,如'mimetype',但同样的错误只是属性名称已更改。我正在使用 postman 来发送数据。 这是我的代码片段。

product.js

import express from 'express';
import mongoose from 'mongoose';
import Product from '../models/product.model';
import multer from 'multer';

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.ts

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: true }
});

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

我找不到解决方案。我从stackoverflow检查了几个解决方案,但没有找到任何解决方案。

2 个答案:

答案 0 :(得分:0)

如果您使用邮递员,请确保在标题和正文中选择“内容类型”“multipart / form-data”,确保选择表单数据,键是“productImage”,类型是文件然后值是您要上传的文件

答案 1 :(得分:0)

使用cURL文件名“图像”发送文件

curl -X PUT  http://www.example.com  -F "image=@/file-path"

在服务器端获取文件名

upload(req, res, (err)=> {
            if (err) {
              console(err);
            }
            let filePath = req.files.image.file; // image is filename in cURL request
});