React native upload file to Azure blob storage

Spread the love

There is no dedicated library to upload files to Azure blob storage from react native. So, we have to use REST API for Azure blob storage. We will be using SAS to authorize our requests and RNFS library to upload the file.

     const localPath = 'complete path of file.';

      // get signature to upload the file

      const sig = 'SAS signature in format "storageURL?signature"'

      const sasContainerUri = sig.url.split('?')[0];

      const container = "containerName";

      const sasToken = sig.url.split('?')[1];
      const date = moment().format('yyyymmdd');

      
      const userIdKey = localPath[0];
      const filePath = localPath[1];

      const fileName = `nameOfFile.extension`;
      const assetPath = `${sasContainerUri}${container}/${date}/${fileName}`;

        try {
          const uploadBegin = response => {
            const jobId = response.jobId;
            console.log('UPLOAD HAS BEGUN! JobId: ' + jobId);
          };

          const uploadProgress = response => {
            const percentage = Math.floor(
              (response.totalBytesSent / response.totalBytesExpectedToSend) * 100,
            );
            console.log('UPLOAD IS ' + percentage + '% DONE!');
          };

          const fileSize = (await RNFS.stat(filePath)).size;

          // upload files
          RNFS.uploadFiles({
            toUrl: assetPath + '?' + sasToken,
            files: [
              {
                name: fileName,
                filename: fileName,
                filepath: filePath,
                filetype: 'application/json', // Update it as per your file type
              },
            ],
            method: 'PUT',
            headers: {
              Accept: 'application/json', // Update it as per your file type
              'x-ms-date': new Date().toUTCString(),
              'x-ms-blob-type': 'BlockBlob',
              'Content-Length': `${fileSize}`, // size in bytes. You can use RNFS 'stat' method
            },
            begin: uploadBegin,
            progress: uploadProgress,
          }).promise.then(response => {
    // You may remove the 200. Because the 201 is returned from Azure
        if (response.statusCode === 200 || response.statusCode === 201) {
              console.log('FILES UPLOADED!');
            } else {
              console.log('SERVER ERROR', response);
            }
          });
        } catch (e) {
          console.log('Error at saving to Azure Storage', e);
        }

Above code will work. There may be some JS syntax error, but logically it will work.

If you face any issues, then (May be some other requirements or other type of blob) check the docs:

Put Blob (REST API) – Azure Storage | Microsoft Learn

Cheers and Peace out!!!