如何使用Node.js将Windows Azure Blob流式传输到客户端?

时间:2012-02-17 12:45:30

标签: node.js azure

我想将Windows Azure Blob(图像)直接发送到客户端;我正在尝试这个:

    blobService.getBlobToStream('images', req.url, res, function(err, blob) {
    if (!err) {
        res.writeHead(200, { 'Content-Type': blob.contentType });
    } else {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end(err);
    }
});

我正在尝试将Blob流直接传递给响应流;这有用吗?在Firefox中,我收到一条消息:"图像无法显示,因为它包含错误"。看看Firebug,图像的大小为0。

2 个答案:

答案 0 :(得分:5)

这似乎对我有用(如果有任何帮助吗?):

var azure = require('azure');
var http = require('http');
http.createServer(function (req, res) {
    var blobService = azure.createBlobService("xxx", "yyy", "blob.core.windows.net").withFilter(new azure.ExponentialRetryPolicyFilter());
    blobService.getBlobToStream('container', 'image.png', res, function(error){
        if(!error){
            res.writeHead(200, {'Content-Type': 'image/png'});
            res.end();
        }
        else
        {
            console.log('error');
            console.log(error);
            res.end();
        }
    });
}).listen(8080, "127.0.0.1");

<强>更新

刚想通了。 req.url将有一个前导斜杠(/)。我估计这与你的图像文件名不符。

答案 1 :(得分:0)

使用azure-storage@2.10.2后,在完成响应后写入响应时出现错误。我还注意到getBlobToStream是自动处理内容类型的。

const storage = require('azure-storage');
const blobService = storage.createBlobService(azureStorage.account, azureStorage.key); // if you want aren't using the same azure env vars

blobService.getBlobToStream(config.switchConfigStorage.container, 'image.png', res, function(error, blob){
  if(!error){ // blob retrieved
    console.log(blob); // good for debugging and possibly more processing
    res.end(); // no need to writeHead
  }else{
    console.log(error);
    res.end();
  }
});