问题描述
我正在为我的 Angular 应用程序使用 CKEditor (@ckeditor/ckeditor5-build-classic)。将图像从前端上传到后端时遇到问题。后端路由运行良好。我在 Postman 上对其进行了测试以成功发布图像。但是当我使用 CKFinder 将图像从 Ckeditor 上传到 Express 后端时,它给出了“MulterError: Unexpected field”。 这是我上传图片的 Express Route。
router.post('/archive',upload.single('file'),function(req,res,next) {
if(!req.file) {
return res.status(500).send({ message: 'Upload fail'});
} else {
html = "";
html += "<script type='text/javascript'>";
html += " var funcNum = " + req.query.CKEditorFuncNum + ";";
html += " var url = \"/public/images/" + req.file.filename + "\";";
html += " var message = \"Uploaded file successfully\";";
html += "";
html += " window.parent.CKEDITOR.tools.callFunction(funcNum,url,message);";
html += "</script>";
res.send(html);
//req.body.imageUrl = 'http://public/images/' + req.file.filename;
gallery.create(req.body,function (err,gallery) {
if (err) {
console.log(err);
return next(err);
}
res.json(gallery);
});
}
});
这是我在组件中用于将图像保存到后端的角度代码。
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
public editor = ClassicEditor;
public config:any = {
ckfinder: {
options: {
resourceType: 'Images'
},uploadUrl: 'http://localhost:3000/gallery/archive/'
}
}
我认为问题出在我的 uploadUrl 上,但我不知道它是什么。有人可以请指点正确的方向吗?任何帮助是极大的赞赏。谢谢。
编辑
我的 Multer 配置:
const storage = multer.diskStorage({
destination: (req,file,cb) => {
cb(null,'./public/images');
},filename: (req,cb) => {
//console.log(file);
var filetype = '';
if(file.mimetype === 'image/gif') {
filetype = 'gif';
}
if(file.mimetype === 'image/png') {
filetype = 'png';
}
if(file.mimetype === 'image/jpeg') {
filetype = 'jpg';
}
cb(null,'image-' + Date.Now() + '.' + filetype);
}
});
const upload = multer({storage: storage});
解决方法
这是表明 fieldName
不匹配的错误。您已在后端指定 fieldname
为 'file'
,因此当您向后端发送图像时,您需要在前端指定相同的名称 'file'
。
或者您可以将后端代码从 upload.single('file')
更改为 upload.any()
。