DEV Community

Cover image for Upload files to Azure Blob Storage with React
Shubham
Shubham

Posted on

Upload files to Azure Blob Storage with React

We can directly upload large files (zip,.mp4, .mp3, .pdf, or any other type) to blob storage via browser with a Shared Access Signature (SAS) token generated from account.

In this example we have used CRA to integrate blob storage code.

We will cover :-

  1. Generating SAS token, Container Name, Storage Name
  2. Uploading file to Blob
  3. Getting the list of all files uploaded to blob

Let's Start :-

Let's assume you have your account setup with Azure and have all necessary permission to create container.

Once you have CRA ready, we will need to use @azure/storage-blob package to upload files.

Now we will need to set up storage account name and container name. Container name is something where all your files resides. I would recommend you to follow this link to set up blob level configuration.

https://docs.microsoft.com/en-us/azure/developer/javascript/tutorial/browser-file-upload-azure-storage-blob

Once you are done with the setup we can start some coding. let's say below are the configuration values.

const sasToken = process.env.storagesastoken || "sv=2020-02-10&ss=bfqt&srt=sco&sp=rwdlacuptfx&se=2021-05-28T16:49:40Z&st=2021-05-24T08:49:40Z&spr=https&sig=Ce0EinaxCMsiqnNfo9wCRr8%3D"; 
const containerName = `importfiles`;
const storageAccountName = process.env.storageresourcename || "storagename"; 
Enter fullscreen mode Exit fullscreen mode

while creating the token we need to set start date and the end date with other permission like read, write, delete.

image

Let's create the file and put the code to choose the file from the folder

const DisplayForm = () => (
    <div>
      <input type="file" onChange={onFileChange} key={inputKey || ''} />
      <button type="submit" onClick={onFileUpload}>
        Upload!
      </button>
    </div>
  );
Enter fullscreen mode Exit fullscreen mode

Now we are all set and we have everything to upload files over the blob storage, so let's see the code for blob Upload.

const uploadFileToBlob = async (file) => {
  if (!file) return [];

  // get BlobService = notice `?` is pulled out of sasToken - if created in Azure portal
  const blobService = new BlobServiceClient(
    `https://${storageAccountName}.blob.core.windows.net/?${sasToken}`
  );
  // get Container - full public read access
  const containerClient = blobService.getContainerClient(containerName);

  // upload file
  await createBlobInContainer(containerClient, file);

  // get list of blobs in container
  return getBlobsInContainer(containerClient);
};
Enter fullscreen mode Exit fullscreen mode

Once we pass the file object as argument to the above function it will call createBlobInContainer function. In this function along with file we can also pass the metadata like UserName, UserId etc so that we can trigger some azure function.

await blobClient.setMetadata({UserName : 'shubham'});
Enter fullscreen mode Exit fullscreen mode

Another use case can be updating the file path in the DB, in that case we will require metadata to map the files.

Once we are able to upload the files in blob it executes getBlobsInContainer function which will return all the files in your storage account. This function is optional and depends on you.

const getBlobsInContainer = async (containerClient) => {
  const returnedBlobUrls = [];
  for await (const blob of containerClient.listBlobsFlat()) {
    // if image is public, just construct URL
    returnedBlobUrls.push(
      `https://${storageAccountName}.blob.core.windows.net/${containerName}/${blob.name}`
    );
  }

  return returnedBlobUrls;
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

This is one way of uploading file to blob and the code which I have put here is the basic one, we can extend our code and put some checks for error handling, getting the progress of files.

We can use Redux with middlewares in case of complex architecture.

The final code is on Github

Top comments (0)