Ali Khalifa
Ali Khalifa

Reputation: 81

Uploading image to azure blob storage using React

I am trying to upload image from react to azure blob storage but the request fails with error :

TypeError: Cannot read properties of undefined (reading 'size') at BlockBlobClient.uploadFile

here is a sample of code trying to achieve it :

import { BlobServiceClient } from '@azure/storage-blob';

const account = process.env.REACT_APP_AZURE_ACCOUNT_NAME;
const sas = process.env.REACT_APP_SAS_TOKEN;

const containerName = 'usercontainer';
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net/?${sas}`,
);

export const uploadToBlob = async (file) => {
  const containerClient = blobServiceClient.getContainerClient(containerName);

  const blobName = file.src + new Date().getTime();
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  const uploadBlobResponse = await blockBlobClient.uploadFile(file.src);
  console.log(
    `Upload block blob ${blobName} successfully`,
    uploadBlobResponse.requestId,
  );
  
};

Upvotes: 0

Views: 1063

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136256

There are a few issues here:

  1. You are calling uploadFile method which is only available in NodeJS runtime and is not available in the browser. Please see documentation of this method here: https://learn.microsoft.com/en-us/javascript/api/@azure/storage-blob/blockblobclient?view=azure-node-latest#@azure-storage-blob-blockblobclient-uploadfile.
  2. The method you would want to use is uploadData which expects an object of type Blob. Considering you have a data URL, you would need to create a Blob object out of it. Please see this question regarding converting a data URL to Blob: Blob from DataURL?

Upvotes: 1

Related Questions