3
votes

I'm trying to upload an image file from an html page to azure blob storage. So far I have written a web service to create an SAS for my blob container. From this I have created a uri of the format "blob address" / "container name" / "blob name" ? "sas". I have an upload control on my html page.

I have then tried to upload the file using the following code:

var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("PUT", blobPath);
xhr.send(upFile.files[0]);

where blobPath is the uri as above and upFile is my html upload control.

When I try to upload a file the uploadFailed routine is triggered. So: Is this the right way to do this? How do I trap the error returned by the upload so that I can see what is going wrong?

My sas looks like: "sr=c&si=mypolicy&sig=onZTE4buyh3JEQT3%2B4cJ6uwnWX7LUh7fYQH2wKsRuCg%3D"

Any help appreciated, thanks.

2

2 Answers

5
votes

This is certainly the right way however there're a few things:

  1. You have to include x-ms-blob-type request header in your request and it's value should be BlockBlob.
  2. Also please realize that for this to work, you would need to host your HTML page in the same storage account because CORS is not supported in Azure Blob Storage as of today. So if your html page is hosted in some other domain, you would get error because of CORS.

You may find these blog posts useful for uploading blobs using SAS and AJAX:

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/

0
votes

I have now found a solution that works for this problem. My upload now works as follows:

  • I read the file as a DataURL into a FileReader

  • I slice the returned string up and send each slice up to the server where it is stored in a session variable

  • Once the whole file has been sent up I call another web service which glues the slices back together and turns the result into a byte array

  • The byte array is then stored as a file in local storage in azure

  • Finally the file is transferred from local storage into blob storage

See code at:

Upload files from html to azure