2016-11-18 17 views
1

我正在編寫一個快速應用程序,其中一個端點接收圖像,然後將該圖像發送給第三方Api。我使用multer將圖像保存到磁盤,並且我具有圖像的相對文件路徑,但我試圖調用的API需要實際圖像或圖像url。問題是我只傳遞一個包含文件路徑的字符串值給圖像。下面是我目前:鑑於本地相對於圖像的URL,我如何獲得實際圖像發送

var multer = require('multer') 
var storage = multer.diskStorage({ 
    destination: function(req, file, cb) { 
     cb(null, './uploads/'); 
    }, 
    filename: function(req, file, cb) { 
     cb(null, Date.now() + file.originalname); 
    } 
}); 
var upload = multer({ storage: storage }); 

,我需要在這裏所說的圖像在此API調用:

router.post('/images/tags/info/image', upload.single('fileName'), function(req, res, next) { 
    console.log(req.file.path); 
    var imageUrl = req.file.path; 
    app.models.predict('APP_KEY', imageUrl).then(
     function (response) { 
      var responseJson = JSON.stringify(response.data.outputs[0].data.concepts); 
      var data = collectTags(responseJson); 
      data.then(function(value) { 
       res.json(value); 
      }); 
     }, 
     function (err) { 
      console.log(err); 
     }); 
}); 

當我console.log(req.file.filePath),我得到一個有效的文件路徑,但我需要的實際圖像進入app.models.predict(API_KEY, image)

+0

當你刪除'.path',只是送什麼情況'req.file' –

+0

我得到一個400錯誤與'badrequest' –

+0

'數據: {狀態: {代碼:11100, 描述:「壞請求格式', details:'無效的json路徑\'在請求中輸入[0] .data.image.destination \'。 }}}' –

回答

1

您可以從文件系統讀取圖像並將其發送到api。
例如

 const bitmap = await q.nfcall(fs.readFile,req.file.path); 
     //remove the temp image 
     fs.unlink(req.file.path);   
     const buffer = new Buffer(bitmap).toString('base64'); 
     app.models.predict('APP_KEY', buffer); 

實施例(使用異步/等待)發送圖像爲base64。

+0

'const bitmap = await q.nfcall(fs.readFile,req.file.path);',它表示q是一個意外的標識符! –

+0

我使用q promise,promisify,但你可以用你自己的藍鳥或es6承諾來代替。這只是爲了處理異步代碼。 – Hosar

+0

你能寫出完整的解決方案嗎?我在'q.nfcall'部分遇到了一些問題 –