Need help downloading image from Azure Blobs using NodeJS

后端 未结 1 1082
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 11:35

I got most of the code from the NodeJS Blob quickstart from azure, I am able to upload files including images successfully and I can see them in the azure storage dashboard jus

相关标签:
1条回答
  • 2021-01-21 11:47

    It sounds like you want to download or show the images stored in Azure Blob Storage, but the container of these images is not public. It's very similar with the SO thread Azure file image path using java.

    The solution is to generate a blob url with SAS signature for downloading or directly showing in the browser, you can refer to the offical document Using shared access signatures (SAS) and Manage anonymous read access to containers and blobs to know the concept.

    Here is the sample code in Node for generating a blob url with SAS signature, which comes from here.

    To create a Shared Access Signature (SAS), use the generateSharedAccessSignature method. Additionally you can use the date helper functions to easily create a SAS that expires at some point relative to the current time.

    var azure = require('azure-storage');
    var blobService = azure.createBlobService();
    
    var startDate = new Date();
    var expiryDate = new Date(startDate);
    expiryDate.setMinutes(startDate.getMinutes() + 100);
    startDate.setMinutes(startDate.getMinutes() - 100);
    
    var sharedAccessPolicy = {
      AccessPolicy: {
        Permissions: azure.BlobUtilities.SharedAccessPermissions.READ,
        Start: startDate,
        Expiry: expiryDate
      }
    };
    
    var token = blobService.generateSharedAccessSignature(containerName, blobName, sharedAccessPolicy);
    var sasUrl = blobService.getUrl(containerName, blobName, token);
    

    Note: The code above is based on npm package azure-storage v2 via npm install azure-storage, not the preview version v10-Preview via npm i @azure/storage-blob or follow the offical document Quickstart: Upload, download, list, and delete blobs using Azure Storage v10 SDK for JavaScript (preview) to install. For using v10 APIs to generating the SAS url, you can refer to my code for SO tread Azure file image path using java in Java which APIs are similar with these for Node.

    Or just to concat a normal blob url with token to get a url with SAS like below, so you can just generate a token to apply at the end of any blob url.

    var sasUrl = blobUrl + token;
    

    Then, you can use the url with SAS to show in browser via <img src="<sas url>"> or directly download it using Http client without any additional authentication until the expiry time.

    0 讨论(0)
提交回复
热议问题