Search code examples
file-uploadazure-storageimage-rendering

How to read image stored in azure storage by using url


I upload the image by using azure blobclientservice as belows

 let fr = new FileReader();

  let result = {};

  fr.onload = async function () {
    var data = fr.result;

    await blockBlobClient
      .uploadData(data, {
        concurrency: 20,
        blobHTTPHeaders: {
          blobContentType: photo.type,
        },
      })
      .then((res) => {
        result = res;
        console.log(res);
      })
      .catch((error) => {
        console.log(error);
        result.error = true;
      });
  };
  fr.readAsArrayBuffer(photo);

And I got the url from the response successfully. I hope to use this url as the src in image tag in html instead of download all data from the storage. But it doesn't show the image and I can only see alt instead of image. I think it is possible to read the image by using url when it is stored in aws s3 bucket as public. I want the same functionality in azure storage. Is it possible? I will be appreciative if somebody helps me.


Solution

  • Your image should be able to show on your page with:

    <img src="the_url_of your_image">
    

    You could access blob with Blob URL(https://{storage-name}.blob.core.windows.net/{container-name}/{test.png}) when your image blob is public.

    enter image description here

    If the access level is private, you could access the image blob with SAS. And the URL looks like https://{storage-name}.blob.core.windows.net/{container-name}/{test.png}?{Blob SAS token}.

    Try to generate Blob SAS token with generateBlobSASQueryParameters.

    // Generate service level SAS for a blob
    const blobSAS = generateBlobSASQueryParameters({
        containerName, // Required
        blobName, // Required
        permissions: BlobSASPermissions.parse("racwd"), // Required
        startsOn: new Date(), // Optional
        expiresOn: new Date(new Date().valueOf() + 86400), // Required. Date type
        cacheControl: "cache-control-override", // Optional
        contentDisposition: "content-disposition-override", // Optional
        contentEncoding: "content-encoding-override", // Optional
        contentLanguage: "content-language-override", // Optional
        contentType: "content-type-override", // Optional
        ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, // Optional
        protocol: SASProtocol.HttpsAndHttp, // Optional
        version: "2016-05-31" // Optional
      },
      sharedKeyCredential // StorageSharedKeyCredential - `new StorageSharedKeyCredential(account, accountKey)`
    ).toString();