从azure-blob获取图像并将其发送到客户端,而无需使用节点服务器在本地保存

问题描述

我想从azure blob存储中获取图像并将其发送到客户端,而不将其保存在本地。我能够从Blob存储中获取图像并将其保存到本地文件,但是在不将其保存到本地的情况下却很难将其发送到客户端。请在下面找到代码

    const containerClient = blobServiceClient.getContainerClient(containerName);
    const blockBlobClient = containerClient.getBlobClient(blobName);

    const downloadBlockBlobResponse = await blockBlobClient.download(0);
    console.log('\nDownloaded blob content...');
    let f = await streamToString(downloadBlockBlobResponse.readableStreamBody)
    
    reply.type('image/jpg').send(f)

streamToString函数如下

     async function streamToString(readableStream) {
        return new Promise((resolve,reject) => {
        const chunks = [];
        readableStream.on("data",(data) => {
            chunks.push(data.toString());
        });
        readableStream.on("end",() => {
            resolve(chunks.join(""));
        });
        readableStream.on("error",reject);
     });
}

运行此代码时,我在浏览器中出现空白屏幕

enter image description here

解决方法

如果要从天蓝色的blob存储中获取图像并将其发送到客户端而不在本地保存,则节点服务器向客户端发送SAS token到客户端,客户端将直接从Azure存储中获取该图像我认为是更好的解决方案。这也减轻了节点服务器的压力:可以生成SAS令牌并将其发送到客户端,无需从存储读取数据。

尝试下面的代码来生成SAS令牌:

var azure = require('azure-storage');
    var connString = "your storage connection string";
    var container ="your container name";
    var blobName = "your image name"
    var blobService = azure.createBlobService(connString);

    // Create a SAS token that expires in an hour
    // Set start time to five minutes ago to avoid clock skew.
    var startDate = new Date();
    startDate.setMinutes(startDate.getMinutes() - 5);
    var expiryDate = new Date(startDate);
    expiryDate.setMinutes(startDate.getMinutes() + 60);
    


    var sharedAccessPolicy = {
        AccessPolicy: {
            Permissions: [azure.BlobUtilities.SharedAccessPermissions.READ],//grent read permission only
            Start: startDate,Expiry: expiryDate
        }
    };
    
    var sasToken = blobService.generateSharedAccessSignature(container,blobName,sharedAccessPolicy);
    
    var response = {};

    response.image = blobService.getUrl(container,sasToken);
    
    res.send(response);

结果: enter image description here

客户端可以使用此图像URL直接从存储中访问该图像:

enter image description here

尝试将imageURL转换为base64图像内容,以便您可以直接基于图像内容保存/显示图像:

<html>

<body>
    <img id="displayImg">
</body>


<script>

var nodeResult = {"image":"https://stantest1016.blob.core.windows.net/stantest/test.jpeg?st=2020-10-26T04%3A53%3A51Z&se=2020-10-26T05%3A53%3A51Z&sp=r&sv=2018-03-28&sr=b&sig=ZjY3LYbgvMn%2BSr4dAEUoqidVRT4YyH1FcW1DeKlpjYo%3D"}


function getImageData(nodeResult){


var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var reader = new FileReader();
        reader.readAsDataURL(this.response);
        reader.onload = function() {
            document.getElementById('displayImg').src = reader.result;
        }
  };
    
   
    
  };
  xhr.open('GET',nodeResult.image);
  xhr.responseType = 'blob';
  xhr.send();

}


getImageData(nodeResult);
</script>

</html>

结果:

enter image description here

标签的详细信息: enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...