azureazure-blob-storageazure-sdk-js

BlobClient#generateSasUrl automatically %-encode blob path


const { BlockBlobClient, BlobSASPermissions } = require("@azure/storage-blob");

const blobClient = new BlockBlobClient(
  "DefaultEndpointsProtocol=https;AccountName=yyyy;AccountKey=xxxx;EndpointSuffix=core.windows.net",
  "test",
  "hoge/huga/baz.txt"
);

const expiresOn = new Date();
expiresOn.setMinutes(expiresOn.getMinutes() + 5);
const h = blobClient.generateSasUrl({ expiresOn, permissions: BlobSASPermissions.from({ read: true })}).then((res) => {
  console.log(res);
});

Executing this script, which uses Azure JavaScript SDK, outputs https://yyyy.blob.core.windows.net/test/hoge%2Fhuga%2Fbaz.txt?sv=2024-05-04&se=2024-07-09T03%3A38%3A03Z&sr=b&sp=r&sig=wHPR6FOUyvXWdQafJ%2F8deC1lVH%2Fl0%2Fu4ZGqqLcsJDmU%3D.

Is this expected behavior? How can I make path to be /test/hoge/huga/baz.txt?


Solution

  • Is this expected behavior? How can I make path to be /test/hoge/huga/baz.txt?

    Yes, it is expected behavior, you can change the expected(decoded) path using below code.

    Code:

    const { BlockBlobClient, BlobSASPermissions } = require("@azure/storage-blob");
    
    const blobClient = new BlockBlobClient(
      "DefaultEndpointsProtocol=https;AccountName=venkat891;AccountKey=r4kv43+pifLxxxxxx;EndpointSuffix=core.windows.net",
      "sample",
      "data/store/001.csv"
    );
    
    const expiresOn = new Date();
    expiresOn.setMinutes(expiresOn.getMinutes() + 5);
    
    blobClient.generateSasUrl({ expiresOn, permissions: BlobSASPermissions.from({ read: true })})
      .then((res) => {
        console.log('Encoded URL:', res);
    
        const url = new URL(res);
        const encodedPath = url.pathname;
        const decodedPath = decodeURIComponent(encodedPath);
        const decodedUrl = url.origin + decodedPath + url.search;
    
        console.log('Decoded URL:', decodedUrl);
      });
    

    Output:

    PS C:\Users\xxxvexxkat\xxx> node example.js
    Encoded URL: https://venkat891.blob.core.windows.net/sample/data%2Fstore%2F001.csv?sv=2024-05-04&se=2024-07-09T04%3A15%3A24Z&sr=b&sp=r&sig=zBG%2Bxe90xxxxxxxx
    Decoded URL: https://venkat891.blob.core.windows.net/sample/data/store/001.csv?sv=2024-05-04&se=2024-07-09T04%3A15%3A24Z&sr=b&sp=r&sig=zBGxxxxx
    

    enter image description here

    I also checked the blob URL is working fine.

    enter image description here