2016-09-20 39 views
0

美好的一天,將上傳的文件分配到環回的模型屬性

我是node.js生態系統的新手,請原諒我是初學者。我基本上想要配置loopback,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")); 

有人可以幫我嗎?我嘗試做的app.use()配置,我通過搜索通過stackoverflow /谷歌之前看到,但似乎這樣做是無效的,因爲打印一個console.log內部似乎並沒有做什麼(可能沒有被稱爲)

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

謝謝!

回答

0

好的。離開了一段時間後,我能夠找到一個方法如何做到這一點。請注意,只有管理員訪問我的應用程序上傳文件,所以我選擇使用內存存儲,他們只是圖像文件,所以我選擇將緩衝區本身存儲到MongoDB文檔(無論如何不是真實的項目)

configure mutler :

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

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

configure前遠程鉤:

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

問候