How to upload a text string directly to Windows Az

2019-08-11 18:14发布

问题:

I would like to upload from a web browser a text/html string as an Azure blob directly to Azure storage (without first going thru the Azure VM/webserver) using browser side javascript. From my research, I understand that one can use Azure REST API + Shared Access Signatures to achieve this from a Silverlight client or thru an MVC 3 view. ( here is the link for controls using SilverLight/MVC3 : http://code.msdn.microsoft.com/silverlight/Silverlight-Azure-Blob-3b773e26#content). I also found a library for uploading using server side javascript with Node.JS https://github.com/jpgarcia/waz-storage-js .

My question is how would one upload a text string to an Azure blob using only browser side javascript and html and SAS (without using Silverlight or MVC) and do so directly to Azure without going thru the web server? How would one pass the string value to the Azure rest api call ( would it accept a JSON string?) ? I looked at the MSDN REST api examples but it was not clear to me how you would pass a text string to be uploaded. Can anyone help with this? Thanks in advance.

回答1:

I don't think this can be done. Unless the web page is being hosted from the same blob storage domain, this would be a cross-domain call, which isn't allowed (unless CORS headers are set, which they aren't for blob storage).

In addition, uploading to a blob requires an HTTP PUT request, and I believe most browsers only allow POST and GET.

UPDATE

See comments below, but it looks like some browsers do allow PUT requests. As noted, the same-origin policy can be defeated by serving the original page from the same blob storage account. In that case, the code would look something like this (using jQuery):

$.ajax({
    url: url,
    type: 'PUT',
    data: 'Hello, World!',
    headers: {'Content-Type': 'text/html'}
}).success(function () {
    console.log('Saved successfully.');
});


回答2:

You can upload from the client without touching the MVC site using JavaScript, I have written a blog post with an example on how to do this http://blog.dynabyte.se/2013/10/09/uploading-directly-to-windows-azure-blob-storage-from-javascript/ the code is at GitHub

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