Frank Sposaro
Frank Sposaro

Reputation: 8531

Upload BlockBlob to Azure Storage using React

I haven't been able to get a working example. My following example tells me that the createBlockBlob method is undefined.

Note: I've also tried createBlockBlobFromLocalFile and passed in the filename and still no luck.

import React from 'react';
var storage = require('azure-storage');

const CONNECTION_STRING = "MYCONNECTIONSTRING";
const BlockBlobContainerName = "MYCONTAINERNAME";
const BlobName = "MYBLOBNAME";

class NumberUploader extends React.Component {

   render() {
      return (
         <div className="App">
         <input type="file" onChange={ (e) => this.buttonClick(e.target.files[0]) } />
         </div>
      );
   }

   buttonClick(myFile) {
      var blobService = storage.createBlobService(CONNECTION_STRING);
      blobService.createContainerIfNotExists(BlockBlobContainerName, function (error) {
         if (error) {
            console.log("error creating container");
         }
      });
      blobService.createBlockBlobFromBrowserFile(BlockBlobContainerName, BlobName, myFile, function (error, result, response) {
         if (error) {
            alert('Upload failed, open browser console for more detailed info.');
            console.log(error);
         } else {
            setTimeout(function () { // Prevent alert from stopping UI progress update
               alert('Upload successfully!');
            }, 1000);
         }
      });
   }
};
export default NumberUploader;

Edit: Visual Studio provides a really good web app template running .Net Core serving React. I was able to use the following code on the server to get the SASToken and pass it to React. From there, you can use the browser file upload method with the SAS.

    static string GetAccountSASToken()
    {
        // To create the account SAS, you need to use your shared key credentials. Modify for your account.
        const string ConnectionString = "GET_STRING_FROM_STORAGE_ACCOUNT";
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);

        // Create a new access policy for the account.
        SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
        {
            Permissions = SharedAccessAccountPermissions.Read | SharedAccessAccountPermissions.Write | SharedAccessAccountPermissions.List,
            Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,
            ResourceTypes = SharedAccessAccountResourceTypes.Service,
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
            Protocols = SharedAccessProtocol.HttpsOnly
        };

        // Return the SAS token.
        string token = storageAccount.GetSharedAccessSignature(policy);
        return token;
    }

Upvotes: 2

Views: 5759

Answers (2)

Xiaoning Liu - MSFT
Xiaoning Liu - MSFT

Reputation: 329

Here are some differences between storage JS v2 and V10 SDK regarding browser scenarios support:

  1. V10 support browser scenarios with npm package and classic single JS bundle file; V2 only supports browser usage with classic single JS bundle file like Peter Pan's sample.

  2. V10 doesn't support SharedKeyCredential in browsers, while V2 supports.

So, if you are building a React Web APP and importing storage SDK using npm dependency. Please use V10. Also please don't use account name and key in browsers, because it's not safe.

Upvotes: 2

Peter Pan
Peter Pan

Reputation: 24138

I see you were using Azure Storage SDK v2 for JavaScript to upload file in React from Browser to Azure Blob Storage. There is a similar SO thread How to upload folder into azure automatically? which I had answered with a completed code in JavaScript. I think it can help you to write React code and make it works in Browser.

According to your description and codes, I have some suggestions for you while using Azure Storage JS SDK v2.

  1. Based on my experience, there are some incompatible with Node.js and browser. So you can not use createBlockBlobFromLocalFile method in browser to upload files.
  2. Please refer to the document Azure Storage JavaScript Client Library Sample for Blob Operations to import azure-storage.blob.js in your HTML file for blob operations as below.

    <script src="azure-storage.blob.js"></script>
    

    or an online version.

    <script src="https://dmrelease.blob.core.windows.net/azurestoragejssample/bundle/azure-storage.blob.js"></script>
    
  3. Then, you can use createBlockBlobFromBrowserFile method in browser.

Meanwhile, a new version of Azure Storage JS SDK is v10 which seems to improve compatibility, that you can pay attention to its APIs marked with "ONLY AVAILABLE IN NODE.JS RUNTIME" or "ONLY AVAILABLE IN BROWSERS" for differences between Node.js and browsers runtime.

Hope it helps.

.

Upvotes: 2

Related Questions