2015-12-09 22 views
0

我有自定義創建方法我正在嘗試爲我的Sails.js應用程序中的Founder模型添加該方法。該應用程序包含文件和常規表單字段。遵循本教程的建議:http://www.shanestillwell.com/2014/04/14/essential-nodejs-development-concepts-p1/ 我試圖將大量控制器代碼卸載到Founder模型中進行處理。這使得有點尷尬,並導致以下錯誤。在Sails.js中傳遞文件流以進行模型處理

TypeError: Cannot read property 'stream' of undefined 

這是這條線在我的模型函數的結果:

createFromForm: function(opts, cb){ 
    var id = opts.id; 
    var params = opts.params; 
    var newFilename = opts.avatartwo._files[0].stream.filename; 

在第四行。現在在控制器中,類似的代碼將遵循Sails語法:

var newFilename = opts.req.file('avatartwo')_files [0] .stream.filename;

我TRED只是寫的req.file('avatartwo')結果到我通過進入該模型功能的選項:

var opts = { 
    params: params, 
    id: id, 
    avatartwo: req.file('avatartwo') 
    }; 

儘管這似乎是有問題的,但因爲我不是最明智的問題,我不知道爲什麼。我可以在這裏欣賞一些解釋。謝謝!

回答

0

要處理sailsjs中的文件上傳,請使用以下代碼。

var uploadedFile = req.file('some_file').upload({ 
    dirname: 'path to store the file',/* optional. defaults to assets/uploads I guess*/ 
    saveAs: 'new file name', /* optional. default file name */ 
    maxBytes: 5 * 1024 * 1024 //5 MB 
}, function(err, uploadedFiles) { 
    if (err) { 
     return res.json(500, err); 
    } else if (uploadedFiles.length === 0) { 
     // handle if no files were uploaded 
    } else { 
     // do processing with file descriptor available at uploadedFiles[0].fd 
     // pass to model in your case 
     var opts = { 
       params: params, 
       id: id, 
       avatartwo: uploadedFiles[0].fd 
     }; 

    } 
});