Sarah
Sarah

Reputation: 1293

Azure storage blob library download blob to local machine

I am following this tutorial and trying to see how I can download the blob file on my local machine

https://learn.microsoft.com/en-us/azure/storage/blobs/quickstart-blobs-javascript-browser#prerequisites

And a little bit from here https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/storage/storage-blob#download-a-blob-and-convert-it-to-a-string-browsers

This is a web app using JavaScript.

The following lines of code work well and I can see the content of the file in console.log Instead of seeing it in console.log, I want the user to be able to download the file to their local machine. So maybe giving a path or something.

I have comment the code that I need help with. It runs but does nothing. I am not seeing a message to download to local.

const downloadFiles = async () => {
  

    if (fileList.selectedOptions.length > 0) {
        //reportStatus("downloading files...");
        for (const option of fileList.selectedOptions) {
            console.log("option.text", option.text);
            
            try {
                const blobClient = containerClient.getBlobClient(option.text);
                console.log("BlobClient",blobClient)
                
                // Hoping this line of code would do the trick
                var blobResponse = await blobClient.downloadToFile(option.text);
                //////

                const downloadBlockBlobResponse = await blobClient.download();
                console.log("downloadBlockBlobResponse", downloadBlockBlobResponse);
               const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody);
               console.log("Downloaded blob to string 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);
                });
              }

              // [Node.js only] A helper method used to read a Node.js readable stream into a Buffer
                async function streamToBuffer(readableStream) {
                    return new Promise((resolve, reject) => {
                    const chunks = [];
                    readableStream.on("data", (data) => {
                        chunks.push(data instanceof Buffer ? data : Buffer.from(data));
                    });
                    readableStream.on("end", () => {
                        resolve(Buffer.concat(chunks));
                    });
                    readableStream.on("error", reject);
                    });
                }
            }
            catch (error) {
                reportStatus(error.message);
            }
        }
        reportStatus("Done.");
        listFiles();
    } else {
        reportStatus("No files selected.");
    }

/*
    //const containerClient = blobServiceClient.getContainerClient(containerName);
    //console.log("containerClient", containerClient);
    const blobName =  // "MyTest1.csv";
  const blobClient = containerClient.getBlobClient(blobName);
  console.log("blobClient", blobClient);
    try {
        const downloadBlockBlobResponse = await blobClient.download();
        console.log("downloadBlockBlobResponse", downloadBlockBlobResponse);
        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);
          });
        }
    } catch (error) {
        reportStatus(error.message);
    }
    */
};

Upvotes: 2

Views: 1711

Answers (1)

Frank Borzage
Frank Borzage

Reputation: 6796

The downloadToFile method only available in node.js runtime, so you cannot use it to download files to local, you can refer to downloadToFile.

enter image description here

You can try the following methods to download files:

const downloadFiles = async () => {
    if (fileList.selectedOptions.length > 0) {
        reportStatus("downloading files...");
        for (const option of fileList.selectedOptions) {
            console.log("option.text", option.text);
            
            try {
                const blobClient = containerClient.getBlobClient(option.text);
                console.log("BlobClient",blobClient);

                const downloadBlockBlobResponse = await blobClient.download();
                const url =window.URL.createObjectURL(await downloadBlockBlobResponse.blobBody);
                
                downloadURI(url,option.text)
                console.log("Downloaded blob to string content", url);
            }
            catch (error) {
                reportStatus(error.message);
            }
        }
        reportStatus("Done.");
        listFiles();
    } else {
        reportStatus("No files selected.");
    }
};

downloadButton.addEventListener("click", downloadFiles);

function downloadURI(uri, name) 
{
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.click();
};

Upvotes: 3

Related Questions