Upload file to Azure Blob Storage directly from browser?
Asked Answered
O

6

33

Is it possible to create an html form to allow web users to upload files directly to azure blob store without using another server as a intermediary? S3 and GAW blobstore both allow this but I cant find any support for azure blob storage.

Orontes answered 27/3, 2013 at 22:20 Comment(0)
H
15

EDIT November 2019

You can now refer to the official documentation:

Initial answer

There is a New Azure Storage JavaScript client library for browsers (Preview).

(Everything from this post comes from the original article above)

  • The JavaScript Client Library for Azure Storage enables many web development scenarios using storage services like Blob, Table, Queue, and File, and is compatible with modern browsers
  • The new JavaScript Client Library for Browsers supports all the storage features available in the latest REST API version 2016-05-31 since it is built with Browserify using the Azure Storage Client Library for Node.js

We highly recommend use of SAS tokens to authenticate with Azure Storage since the JavaScript Client Library will expose the authentication token to the user in the browser. A SAS token with limited scope and time is highly recommended. In an ideal web application it is expected that the backend application will authenticate users when they log on, and will then provide a SAS token to the client for authorizing access to the Storage account. This removes the need to authenticate using an account key. Check out the Azure Function sample in our Github repository that generates a SAS token upon an HTTP POST request.

Code sample:

  1. Insert the following script tags in your HTML code. Make sure the JavaScript files located in the same folder.

    <script src="azure-storage.common.js"></script/>
    <script src="azure-storage.blob.js"></script/>
    
  2. Let’s now add a few items to the page to initiate the transfer. Add the following tags inside the BODY tag. Notice that the button calls uploadBlobFromText method when clicked. We will define this method in the next step.

    <input type="text" id="text" name="text" value="Hello World!" />
    <button id="upload-button" onclick="uploadBlobFromText()">Upload</button>
    
  3. So far, we have included the client library and added the HTML code to show the user a text input and a button to initiate the transfer. When the user clicks on the upload button, uploadBlobFromText will be called. Let’s define that now:

    <script>
    function uploadBlobFromText() {
        // your account and SAS information
        var sasKey ="....";
        var blobUri = "http://<accountname>.blob.core.windows.net";
        var blobService = AzureStorage.createBlobServiceWithSas(blobUri, sasKey).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
        var text = document.getElementById('text');
        var btn = document.getElementById("upload-button");
        blobService.createBlockBlobFromText('mycontainer', 'myblob', text.value,  function(error, result, response){
            if (error) {
                alert('Upload filed, open browser console for more detailed info.');
                console.log(error);
            } else {
                alert('Upload successfully!');
            }
        });
    }
    </script>
    
Hypochromia answered 2/11, 2017 at 22:33 Comment(3)
How do you do this without showing the SAS key in the source code? I need to do this for a public-facing website.Swing
Your first link no longer works. I'm guessing the answer is now outdated?Visional
The second link referencing the sdk is still active abd the offical sdk for js. Thanks for letting me know, I will try to find a relevant link to replace the broken oneHypochromia
A
12

Do take a look at these blog posts for uploading files directly from browser to blob storage:

http://coderead.wordpress.com/2012/11/21/uploading-files-directly-to-blob-storage-from-the-browser/

http://gauravmantri.com/2013/02/16/uploading-large-files-in-windows-azure-blob-storage-using-shared-access-signature-html-and-javascript

The 2nd post (written by me) makes use of HTML 5 File API and thus would not work in all browsers.

The basic idea is to create a Shared Access Signature (SAS) for a blob container. The SAS should have Write permission. Since Windows Azure Blob Storage does not support CORS yet (which is supported by both Amazon S3 and Google), you would need to host the HTML page in the blob storage where you want your users to upload the file. Then you can use jQuery's Ajax functionality.

Analemma answered 28/3, 2013 at 2:46 Comment(9)
Update: Azure now supports CORS.Navar
BTW, you may want to update your blog post... browsers will throw errors if you try to manually set the content-length header of a request.Boundary
And having solved several other issues along the way (enabling CORS was painful!), I've discovered that apparently you need an authorization header not present in your sample.Boundary
@Boundary Thanks Ron for Content-Length header comment. I have updated my post accordingly. I don't believe you need authorization header because you're using Shared Access Signature which includes necessary authorization information.Analemma
So it turns out your right, the issue was that my authentication header was 'leaking' in from my regular application logic. (oops). once I manually delete the header from this specific call, I move on to a type error about cannot convert object to primitive value -- any ideas? (OK, I think that may be about how I'm deleting the headers... I just love programming, yup yup...)Boundary
@Boundary Would you mind posting this as a separate question with your code? Without looking at the code, it would not be possible to say why you're getting this error.Analemma
I actually figured it out eventually. I was removing my authorization header in an outdated manner that's no longer supported by Angular.Boundary
@GauravMantri, do you have a more recent method for accomplishing file upload from a website form? How do we get around having a SAS token in the HTML source?Swing
@SeaDude: do you have a more recent method for accomplishing file upload from a website form? - Use storage SDK. How do we get around having a SAS token in the HTML source? - You cannot.Analemma
M
5

Now that Windows Azure storage services support CORS, you can do this. You can see the announcement here: Windows Azure Storage Release - Introducing CORS, JSON, Minute Metrics, and More.

I have a simple example that illustrates this scenario here: http://www.contentmaster.com/azure/windows-azure-storage-cors/

The example shows how to upload and download directly from a private blob using jQuery.ajax. This example still requires a server component to generate the shared access signature: this avoids the need to expose the storage account key in the client code.

Mesitylene answered 12/12, 2013 at 12:7 Comment(1)
contentmaster.com/azure/windows-azure-storage-cors this link is 404.Rivera
A
2

You can use HTML5 File API, AJAX and MVC 3 to build a robust file upload control to upload huge files securely and reliably to Windows Azure blob storage with a provision of monitoring operation progress and operation cancellation. The solution works as below:

  1. Client-side JavaScript that accepts and processes a file uploaded by user.
  2. Server-side code that processes file chunks sent by JavaScript.
  3. Client-side UI that invokes JavaScript.

Get the sample code here: Reliable Uploads to Windows Azure Blob Storage via an HTML5 Control

Aglaia answered 27/3, 2013 at 22:32 Comment(1)
This article uses the web server as an intermediary, relaying the chunks to Azure using a custom Javascript chunking method. It's probably slick but not a fit for the question.Symbolist
E
2

I have written a blog post with an example on how to do this, the code is at GitHub

It is based on Gaurav Mantris post and works by hosting the JavaScript on the Blob Storage itself.

Elijah answered 16/10, 2013 at 9:37 Comment(2)
your blog post is not visible anymore :(Mb
No, I am sorry, it is 8 years ago and I do not work for the company that hosted it anymore. The code is still in GitHub but again, it is 8 years old...Elijah
W
0
  1. Configure a proper CORS rule on your storage account.
  2. Generate a Shared Access Signature from your target container.
  3. Install the blob storage SDK: npm install @azure/storage-blob.
  4. Assuming your file is Blob/Buffer/BufferArray, you can do something like this in your code:
import { ContainerClient } from "@azure/storage-blob";

const account = "your storage account name";
const container = "your container name";
const sas = "your shared access signature";
const containerClient = new ContainerClient(
  `https://${account}.blob.core.windows.net/${container}${sas}`
);

async function upload(fileName, file) {
  const blockBlobClient = containerClient.getBlockBlobClient(fileName);
  const result = await blockBlobClient.uploadData(file);
  console.log("uploaded", result);
}

Winn answered 15/4, 2022 at 18:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.