我有一个如下的router.js:
'use strict';
const express = require('express');
const router = express.Router();
const signupController = require('../controller/signup.controller');
const signinController = require('../controller/signin.controller');
const userListController = require('../controller/userList.controller');
const productController = require('../controller/product.controller');
const passport = require('passport');
require('../config/passport')(passport);
router.get('/users', passport.authenticate('jwt', {session: false}), userListController.getUserList);
router.post('/product', productController.addProduct)
router.post('/user/signup', signupController.Signup);
router.post('/user/signin', signinController.Signin);
module.exports = router;
并在productController.addProduct中我有这段代码:
'use strict';
var mongoose = require('mongoose');
var Product = require('../model/product.model');
var multer = require('multer');
var path = require('path');
// File storage configuration
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, '...store some where in filesystem...');
}
});
// File filter configuration
const fileFilter = (req, file, cb) => {
if (path.extname(file) === '.gpg') {
cb(null, true);
} else {
cb(null, false);
}
};
// File upload configuration
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
//fileFilter: fileFilter
});
// Loader module
exports.addProduct = (req, res, next) => {
console.log(req.file);
...
}
如何将上传添加到exports.addProduct =(req,res,next)=> {},所以我可以访问req.file
我尝试过类似的东西,但没有用:
exports.addProduct =(upload.single('productImage'),(req,res,next)=> {}
答案 0 :(得分:0)
我会试试这个:
在productController
中也导出upload
。所以你需要添加:
exports.upload = upload;
// Loader module
exports.addProduct = ... // like in your code
由于路由器功能需要所有回调,请像这样修改router.js
:
router.post('/product', productController.upload, productController.addProduct);
希望有所帮助。
答案 1 :(得分:0)
在您的router.js
中,添加
router.post('/product',productController.upload, productController.addProduct);
在productController.js
中:
module.exports.upload=(upload.single('image')), (request, response, next)=>{
next();
}
在productController.js
module.exports.addProduct=( (request,response, next)=>{
console.log(request.file);
next();
});