我正在使用Node,Express和Handlebars创建一个应用程序,并使用multer上传图像。每次提交表单时,req.file都是未定义的。我花了一整天的时间进行故障排除,但无法弄清楚我做错了什么。
路由器文件:
const express = require('express');
const router = express.Router();
const multer = require('multer');
const mongoose = require('mongoose');
const path = require('path');
const methodOverride = require('method-override');
//Set Storage Engine
const storage = multer.diskStorage({
destination: './public/uploads/images',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() +
path.extname(file.originalname));
}
});
const upload = multer({
storage: storage
}).single('featuredImage');
//Change Featured Image - POST
router.post('/saveImage/:id', (req, res) => {
console.log(req.file);
//removed the rest of the code to keep it simple. req.file here is always undefined.
});
表格
<form action="/saveImage/{{pitch.id}}" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="featuredImage">Featured Image</label>
<input type="file" name="featuredImage" id="featuredImage">
</div>
<input type="submit" value="SAVE">
</form>
app.js 这些要求位于app.js文件中。
const express = require('express');
const exphbs = require('express-handlebars');
const path = require('path');
const passport = require('passport');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const flash = require('connect-flash');
const session = require('express-session');
const methodOverride = require('method-override');
const nodemailer = require('nodemailer');
//Set StaticFolder
app.use(express.static(path.join(__dirname, 'public')));
答案 0 :(得分:1)
您需要添加upload.single('featuredImage')
作为相应路由的中间件,如下所示。
const upload = multer({storage: storage});
//Change Featured Image - POST
router.post('/saveImage/:id',upload.single('featuredImage'), (req, res) => {
console.log(req.file);
//removed the rest of the code to keep it simple. req.file here is always undefined.
});
答案 1 :(得分:0)
请参阅这个问题。它有你正在寻找的答案。
node js multer file upload not working. req.file and req.files always undefined
答案 2 :(得分:0)
使用此:
var fileupload = require("express-fileupload");
app.use(fileupload());
答案 3 :(得分:0)
就我而言,这是图像大小的问题。我通过如下定义 multer limit 解决了这个问题:
const upload = multer({ storage: storage, limits: { fieldSize: 10 * 1024 * 1024 } }); //10MB
我花了很长时间才弄明白。 也许这可以帮助某人