node.js - 从 azure-blob 获取图像并将其发送到客户端,而不使用 Node 服务器本地保存

标签 node.js angular azure-blob-storage fastify

我想从 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

最佳答案

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

尝试使用以下代码生成 SAS token :

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

结果: 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

关于node.js - 从 azure-blob 获取图像并将其发送到客户端,而不使用 Node 服务器本地保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64443295/

相关文章:

javascript - 如何在chart.js中以k格式显示条形值的千位

Angular 8 : "Please add a @NgModule annotation" when including a library into another library

asp.net - 使用Azure blob存储,我们需要应用程序的用户特定文件访问,有什么方法可以实现吗?

javascript - 使用 azure blob 存储 javascript 库并行文件上传 (v12)

java - 将 RAMDirectory 上传到 AzureCloud 会创建 EOF 异常

javascript - Nodejs 运行每日任务

node.js - 如何将此 Mongoose 插件移植到 Mongoose 5

jquery - 来自外部的函数:404 Not Found

javascript - Node google api 电子邮件正文

angular - 通过 CLI 安装 Angular 2 后无法创建新实例