Nodejs API - 多文件上传 - 将 属性 及其值动态添加到 JSON 对象

Nodejs API - multer fileupload - Adding property and its value dynamically to JSON object

在我的用户界面 (angularjs) 中,我创建了新行。每行都有文件上传按钮。我想上传所有文件和元数据,并在一次调用中保存每一行。我 post 到 Nodejs API 的复杂对象有点像下面

var activity = {
  "Id" : 1,
  "Name" : "Test",
  "Steps" : [
    {
      "StepId":1,
      "FileUrl": {fileObject} // this property if bound with the file upload directive 'ng-file-upload' by Daniel Farid
      "Description" : "Save this file"
      },
     {
      "StepId":2,
      "FileUrl": {fileObject} // this property if bound with the file upload directive 'ng-file-upload' by Daniel Farid
      "Description" : "Save this file2"
      }
  ]
}

此 JSON 将 posted 到 Node js API。在 Nodejs 方面,我使用 multer 将上传的文件保存到服务器。我使用 multer 的 .any() 方法获取了 API 中的所有文件,但是我得到了没有 Steps[x].FileUrl 属性.

的 posted 对象

包含有关添加此文件的字段名称信息的文件对象。以下是我在调试器中看到的信息。

Array[2]
length:2
[0]:Object
destination:"C:\DeleteThis\"
encoding:"7bit"
fieldname:"Steps[0][FileUrl]"
filename:"ed13d2a61cb38c43f1f46a221855a896"
mimetype:"image/png"
originalname:"deploy.png"
path:"C:\DeleteThis\ed13d2a61cb38c43f1f46a221855a896"
size:2347
[1]:Object

现在我想做什么,因为我的 posted 复杂对象没有 Steps[0].FileUrl 属性,我想迭代每个文件(即 req.files) 并使用字段名创建此 属性 并将 originalName 作为值分配给它。

我是怎么做到的

var deployment = req.body;
        if(req.files){
            var app = _config.getApplicationConfig(req.body.ApplicationId);
            req.files.forEach(function(f){

                //Move file to the deployment folder.
                _utils.createDirIfNotExist(app.packageDir);
                var newPath =  _utils.DetermineFileName(f.originalname, app.packageDir);
                _fs.renameSync(f.path, path.join(app.packageDir,newPath));
                var newFileName = path.basename(newPath);
                //set the file url to corresponding field
                var evalExp = "deployment." + f.fieldname; //I get evalExpression as  "deployment.Steps[0][FileUrl]"
                eval(evalExp); //Here it fails saying FileUrl is not defined
                evalExp = "deployment." + f.fieldname + "= \"" +  newFileName.toString() + "\""; 
                eval(evalExp);    
            });
        }

有谁知道如何在 运行 时将 属性 分配给对象?

我已经找到解决方法如下 我写了一个将 [] 符号转换为 .符号即。 myobj[myprop] 到 myobj.myprop

var convertToDotNotation = function (keyPath) {
    var bracketSyntaxRegex = new RegExp(/\[([^0-9])\w+\]/g); //matches the javascript property defined in [] syntax but not an array 
    var matches = keyPath.match(bracketSyntaxRegex)
    if(matches && matches.length > 0){
        matches.forEach(function(p){
            //replace '[' with '.' and ']' with emptyspace
            var dotSyntax = p.replace("[",".").replace("]","");
            keyPath = keyPath.replace(p,dotSyntax);
        });
    }
    return keyPath;
}

这会给我“.”可以动态创建 属性 并设置值

的符号
var newFileName = "MyFile.pdf";
var evalExp = "deployment[0].[FileUrl]" ;
var temp = convertToDotNotation(evalExp);
eval(temp + "= \"" +  newFileName + "\""); 

希望对大家有所帮助。