在环回中将上传的文件分配给模型 属性

assigning the uploaded file to the model property in loopback

美好的一天,

我是 node.js 生态系统的新手,请原谅我是初学者。我基本上想配置环回、bodyparser 和 multer 来做一件事,我希望 Phone.imageFile 属性 从上传的图像文件中获得价值。使用 body 作为 form-data 通过邮递员发布我的 Phone 模型数据并且没有额外的 headers 会导致以下错误。

"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/文件夹。我还可以说这些字段被正确读取,因为错误消息没有提到其他必需的 non-nullable 字段

'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"));

有人body能帮帮我吗?我尝试执行之前通过 Whosebug/google 搜索时看到的 app.use() 配置,但似乎这样做是无效的,因为在其中打印 console.log 似乎什么都不做(也许未被调用)

github 回购:https://github.com/silencer07/PinoyDroidMatch

谢谢!

好的。离开一段时间后,我找到了一种方法。请注意,我的应用程序只有管理员权限才能上传文件,所以我选择使用内存存储,而且它们只是图像文件,所以我选择将缓冲区本身存储到 mongodb 文档(无论如何都不是现实生活中的项目)

配置穆勒:

var multer = require('multer');
var storage = multer.memoryStorage();

app.use(multer({storage : storage, }).single("imageFile"));

远程钩子前配置:

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();
});

此致