描述一下问题:如果去掉enctype="multipart/form-data"
,就不会报“ Error: invalid csrf token ”错误,加上enctype
后就报这个错误了。
请各位大大,帮我看一下,要怎么弄,才能不报 csrf 错误,其他的表单都能正常用,只差这个图片上传功能一直无法使用,都整了两天了,硬是无法弄好。
html 代码:
<div class="col-md-10 del-padding">
<form class="form-horizontal" action="/user/upload" method="POST" enctype="multipart/form-data">
<div class="thumbnail text-center">
<img src="/public/Images/default.jpg" class="img-thumbnail">
<div class="upload-box">
<label class="file"><input type="file" name="avatar" id="file"></label>
</div>
</div>
<div class="form-group text-center">
<input type="hidden" name="_csrf" value="yNzdpalm-6yF_T2yfNPhO1wFB56ogwSaOQSE" />
<button type="submit" class="btn btn-primary">保存修改</button>
</div>
</form>
</div>
js 代码:
var express = require("express");
var fs = require('fs');
var path = require("path");
var multer = require('multer');
var router = express.Router();
router.post('/upload', function(req, res, next) {
function mkdirsSync(dirname, mode){
if(fs.existsSync(dirname)){
return true;
}else{
if(mkdirsSync(path.dirname(dirname), mode)){
fs.mkdirSync(dirname, mode);
return true;
}
}
}
mkdirsSync(uploadFolder, 0755);
var uploadFolder = process.cwd()+'/public/upload/Face';
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, folder); //save upload folder
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now());//rename filename
}
});
var upload = multer({ storage: storage }).single('avatar');
upload(req, res, function (err) {
if (err) {
return next(err);
}
console.log(req.file);
req.flash('success_message', '恭喜你,头像上传成功!');
return res.redirect('back');
});
});
1
whypool 2017-11-15 21:48:54 +08:00
需要理解一下 express 的中间件,上传文件这个中间件不是这样用的;
构造函数: constructor() { /** * 上传图片到缓存 */ this.storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, process.cwd() + '/public/tmp/') }, filename: function (req, file, cb) { let name = file.originalname.substr(file.originalname.lastIndexOf('.'), file.originalname.length); cb(null, Date.now() + name) }, fileFilter: function fileFilter(req, file, cb) { if (file.mimetype.substring(0, 'image'.length) == 'image') { cb(null, true);// 接受这个文件 } else { cb(null, false);// 拒绝这个文件 } } }); this.upload = multer({ storage: this.storage, limits: { fileSize: 1024 * 1024 * 10 //10m } }); } 中间价使用: router.post('/upload-img', uploader.upload.single('editorImg'), (req, res) => { req.file }); |