【问题标题】:assigning the uploaded file to the model property in loopback将上传的文件分配给环回中的模型属性
【发布时间】:2016-09-22 14:46:57
【问题描述】:

早安,

我是 node.js 生态系统的新手,所以请原谅我是初学者。我基本上想配置环回、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"));

有人可以帮帮我吗?我尝试执行我之前通过 stackoverflow/google 搜索看到的 app.use() 配置,但似乎这样做是无效的,因为在其中打印 console.log 似乎没有任何作用(可能没有被调用)

github 仓库:https://github.com/silencer07/PinoyDroidMatch

谢谢!

【问题讨论】:

    标签: node.js loopbackjs multer body-parser


    【解决方案1】:

    好的。离开一段时间后,我找到了解决方法。请注意,我的应用程序只有管理员权限才能上传文件,所以我选择使用内存存储,它们只是图像文件,所以我选择将缓冲区本身存储到 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();
    });
    

    问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多