将上传的文件分配到环回的模型属性
问题描述:
美好的一天,将上传的文件分配到环回的模型属性
我是node.js生态系统的新手,请原谅我是初学者。我基本上想要配置loopback,bodyparser和multer来做一件事,我希望Phone.imageFile属性具有来自上传的图像文件的值。通过邮递员发送我的Phone
模型数据与身体作为表单数据和没有额外的头部导致以下错误。
"error": {
"name": "ValidationError",
"status": 422,
"message": "The `Phone` instance is not valid. Details: `imageFile` can't be blank (value: undefined).",
"statusCode": 422,
"details": {
"context": "Phone",
"codes": {
"imageFile": [
"presence"
]
},
"messages": {
"imageFile": [
"can't be blank"
]
}
}
我还可以验证该图像文件正在通过以下配置上载到./phoneImageFiles/文件夹。我也可以说,这些字段正确读取的错误消息并没有提到其他必需的非空的领域
'use strict';
var loopback = require('loopback');
var boot = require('loopback-boot');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = module.exports = loopback();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer({dest:'./phoneImageFiles/', }).single("imageFile"));
有人可以帮我吗?我尝试做的app.use()配置,我通过搜索通过* /谷歌之前看到,但似乎这样做是无效的,因为打印一个console.log内部似乎并没有做什么(可能没有被称为)
github回购:https://github.com/silencer07/PinoyDroidMatch
谢谢!
答
好的。离开了一段时间后,我能够找到一个方法如何做到这一点。请注意,只有管理员访问我的应用程序上传文件,所以我选择使用内存存储,他们只是图像文件,所以我选择将缓冲区本身存储到MongoDB文档(无论如何不是真实的项目)
configure mutler :
var multer = require('multer');
var storage = multer.memoryStorage();
app.use(multer({storage : storage, }).single("imageFile"));
configure前远程钩:
Phone.beforeRemote('**', function (ctx, unused, next) {
var req = ctx.req;
//uploaded using multer
if(req.file){
var imageFile = req.file.buffer;
var fileName = req.file.originalname;
console.log("uploaded file:" + fileName);
var imageFileType = fileName.substring(fileName.indexOf(".") + 1, fileName.length);
req.body.imageFile = imageFile;
req.body.imageFileType = imageFileType;
}
next();
});
问候