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

Fetch image from azure-blob and send it to client without saving locally using node server

我想从 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);
     });
}

当我运行此代码

时,浏览器出现黑屏

如果您想从 Azure Blob 存储中获取图像并将其发送到客户端而不在本地保存,节点服务器将 SAS token 发送到客户端,客户端从 Azure 存储中获取该图像我认为直接将是一个更好的解决方案。也减轻了Node服务器的压力:生成一个SAS token发送给客户端就可以了,不需要从Storage中读取数据。

尝试使用以下代码生成 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,blobName,sasToken);
    
    res.send(response);

结果:

Client-side 可以使用此图像 URL 直接从存储访问此图像:

尝试将图像URL 转换为 base64 图像内容,以便您可以 save/show 图像直接基于其内容:

<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>

结果:

标签详情: