我是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
的问题。
现在任何人都可以帮我解决这个问题。在没有解决问题的情况下继续前进对我来说真是个大问题....
提前致谢。
答案 0 :(得分: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);
}
};