I am working on reactjs/typescript applications. I am trying to download some files from azure storage v2. Below is the sample path I am supposed to download files. In this path, enrichment is the container name, and the rest all are folders. I am trying to download the last modified file from reportdocument folder.
enrichment/report/SAR-1234-56/reportdocument/file1.docsI tried something below.
@action public async reportDownload(sarNumber: string) { let storage = globals.getGlobals('StorageAccount03'); console.log(storage); let containerName = globals.getGlobals('StorageAccount03ContainerName'); let marker = undefined; let allUploadPromise: Array<Promise<unknown>> = []; const config = { path: `/Storage/getsastoken/?storageName=${storage}&containerName=${containerName}`, method: "GET", success: (url: any) => { const containerURL: ContainerURL = new ContainerURL( url, StorageURL.newPipeline(new AnonymousCredential())); const listBlobsResponse = containerURL.listBlobFlatSegment( Aborter.none, marker, ); } }; await handleRequest(config); }From here I am struggling to download the latest modified file from the above path. can someone help me to fix this? Any help would be greatly appreciated. Thank you
02 Answers
It's better to use @azure/storage-blob library and then the code would be something like below instead of directly trying to call blob REST API like you were trying in your code which seems unnecessary reinventing the wheel. The library already does it for you. Refer this for details.
const { BlobServiceClient } = require("@azure/storage-blob");
const account = "<account name>";
const sas = "<service Shared Access Signature Token>";
const containerName = "<container name>";
const blobName = "<blob name>";
const blobServiceClient = new BlobServiceClient(`);
async function download() { const containerClient = blobServiceClient.getContainerClient(containerName); const blobClient = containerClient.getBlobClient(blobName); // Get blob content from position 0 to the end // In browsers, get downloaded data by accessing downloadBlockBlobResponse.blobBody const downloadBlockBlobResponse = await blobClient.download(); const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); console.log("Downloaded blob content", downloaded); // [Browsers only] A helper method used to convert a browser Blob into string. async function blobToString(blob) { const fileReader = new FileReader(); return new Promise((resolve, reject) => { fileReader.onloadend = (ev) => { resolve(ev.target.result); }; fileReader.onerror = reject; fileReader.readAsText(blob); }); }
} The SAS token expiry bothers me.You cannot have a static SAS token that expires sooner unless we can set long expiry (user-delegation SAS token is short lived). Do we really have the capability to create the SAS token dynamically in javascript runtime? I think it's only possible in NodeJS runtime.
1