Upload a File object to azure storage from react js / node js

1.5k views Asked by At

I am trying to browse a file and upload it to azure storage account directly from react js / node js application. Tried with couple of modules 'azure-storage' and '@azure/storage-blob'. I can create/upload a blob with some content manually and upload it to azure storage account, but I don't find a way to upload the File which is selected through 'browse - choose a file (input type=file).

Please suggest me a good approach.

The following is sample code: Here 'file' is a File object browsed through material-ui-dropzone -- DropzoneArea

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

const sharedKeyCredential = new StorageSharedKeyCredential(azureStorageAccount, azureStorageAccessKey);
const serviceClient = new BlobServiceClient(
  // When using AnonymousCredential, following url should include a valid SAS
  `https://${azureStorageAccount}.blob.core.windows.net`,
  sharedKeyCredential
);

let containerExists = false;
for await (const container of containerIter) {
  if (container.name === containerName) {
    containerExists = true;
    break;
  }
}
const containerClient = serviceClient.getContainerClient(containerName);
if (!containerExists) {
  const createContainerResponse = await containerClient.create();
  console.log('Container was created successfully', createContainerResponse.requestId);
}

// below working fine
const content = 'samle content';
const blobName = 'sample.txt';
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
console.log(`Upload block blob ${blobName} successfully`, uploadBlobResponse.requestId);

// NOT WORKING : here file is a File object
const blobName = file.name;
console.log(blobName);
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const uploadBlobResponse = await blockBlobClient.uploadBrowserData(file);
console.log(`Upload block blob ${file.name} successfully`, uploadBlobResponse.clientRequestId);

Thanks in advance.

1

There are 1 answers

0
Jason Pan On

You can read this blog first.

Upload to Azure Blob Storage with React

I looked at the document and tried it again. The gif animation below should be the result you want.

enter image description here

I quoted the official sample code, because there are requirements for some dependent versions, which cannot be used directly after downloading. I fixed this problem and uploaded it to my own github, you can download it.

When you need to use it in your project, please read the source code carefully and modify the configuration.