2016-06-21 45 views
0

在我的用戶界面(angularjs)中創建新行。每一行都有文件上傳按鈕。我想要將所有文件與元數據一起上傳,並將每一行保存在一次調用中。我發佈到Nodejs API的複雜對象有點像Nodejs API - multer fileupload - 將屬性及其值動態添加到JSON對象

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將被髮布到Node js API。在Nodejs方面,我使用multer將上傳的文件保存到服務器。我使用multer的.any()方法獲取API中的所有文件,但是我獲取了沒有Steps [x] .FileUrl屬性的發佈對象。

該文件對象具有關於添加此文件的字段名稱的信息。以下是我在調試器中看到的信息。

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 

現在我想這樣做,因爲我是貼複雜的對象沒有步驟[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);  
      }); 
     } 

有誰知道如何可以如在運行時的財產分配給一個對象?

回答

0

我已經找到解決方案,如下所示 我已經寫了一個函數,將[]符號轉換爲。符號即, myobj [myprop] to 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 + "\""); 

希望它能幫助別人。