2

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;
    }
2
  • Even when you call createBlockBlobFromBrowserFile are you getting the same error message that createBlockBlob method is undefined? What's the version of azure-storage SDK you're using? Also, I am assuming that you're using a SAS Token. Commented Jun 9, 2019 at 14:07
  • @GauravMantri sorry. I got a little lazy after banging my head on this for 8 hours. I am getting createBlockBlobFromBrowserFile not found. I'm not using a SAS token. I was using a connectionString and set up a CORS rules with wildcards so I can upload with localhost. [email protected] Commented Jun 9, 2019 at 18:42

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

.

6 Comments

I restarted from scratch an tried again ensuring to use @azure/[email protected]. Followed the simple example from the docs "github.com/azure/azure-storage-js/tree/master/blob/samples", but now I'm now hitting SharedKeyCredential is not a Constructor "stackoverflow.com/questions/56520576/…"
@FrankSposaro OK, I will try to help for your restarted code. Meanwhile, my code using v2 SDK works fine I test. I hope you can also try it with React, and mark my post as an answer. Thanks!
Ok. I will go back and try on V2 again. I think I'm not understanding the basics node.js vs react vs browsers. If your code is running serverside, how does that allow the file from the client side be uploaded?
@FrankSposaro please carefully read my code in the SO thread stackoverflow.com/questions/55613356/….
@FrankSposaro Considering for security, I don't recommend to put the account key of your storage in the code of front-end. So you need to generate the blob url with SAS token from backend and pass it to the front-end code for uploading files to the secure blob url. Even you switch to use v10 SDK, don't expose your key in the front-end.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.