2013-12-10 66 views
0

我需要從外部服務器下載圖像並將其動態推送給我的客戶端。使用curl與node.js下載圖像並將其轉換爲base64

外部服務器正在使用SSL和基本身份驗證。花了幾個小時試圖使用'request'和'restler'模塊後,我放棄了並且解決了'curlrequest'模塊,這個模塊工作正常。

我的問題是,由curl下載的二進制圖像數據不會轉換成可讀的base64圖像。我想可能會有一些捲曲的標誌,但我並不確定。任何幫助表示讚賞。

var curl = require('curlrequest'); 

exports.slideImageData = function (req, res){ 
    var id = req.params.id; 
    var prefix = "data:image/png;base64, "; 
    var options = { 
    url: config.jive.domain + 'api/core/v3/people/' + id + '/images/1/data' 
    , user: config.jive.user + ':' + config.jive.pass 
    }; 
    curl.request(options, function (err, result){ 
    if (err){ 
     console.log(err) 
    } else{ 
     var base64Image = new Buffer(result, 'binary').toString('base64'); 
     base64Image = prefix + base64Image; 
     res.send('<img src="' + base64Image + '"/>'); 
    } 
    }); 
} 

要添加更多的上下文,這裏是圖像在客戶端中的樣子。有意使用橢圓截斷base64編碼。

<img src="data:image/png;base64, /VBORw0KGgoAAAANSUh ... AAAABJRU5E/UJg/Q=="> 

回答

0

正確的答案,這是丹科答案的變體。

var curl = require('curlrequest'); 

exports.slideImageData = function (req, res){ 
    var id = req.params.id; 
    var prefix = "data:image/png;base64, "; 
    var options = { 
    url: config.jive.domain + 'api/core/v3/people/' + id + '/images/1/data' 
    , user: config.jive.user + ':' + config.jive.pass 
    , encoding: null 
    }; 
    curl.request(options, function (err, result){ 
     var base64Image = new Buffer(result, 'binary').toString('base64'); 
     base64Image = prefix + base64Image; 
     res.send('<img src="' + base64Image + '"/>'); 
    }); 
} 
0

嘗試:

var options = { 
    url: config.jive.domain + 'api/core/v3/people/' + id + '/images/1/data' 
    , user: config.jive.user + ':' + config.jive.pass 
    , RAW: 1 
    }; 

這就是它需要得到的數據返回給你作爲一個緩衝區,而不是一個字符串。 Node.js get image from web and encode with base64顯示如何使用請求執行此操作。

+0

當我嘗試使用RAW時,出現錯誤:無法初始化。此外,當我嘗試使用編碼:空,我得到的錯誤:未知的編碼:[對象對象]。 https://github.com/chriso/curlrequest –

+0

嘗試使用它們的RAW示例,它具有稍微不同的語法:https://github.com/jiangmiao/node-curl – dankohn