locked
Uploading a file to Azure Storage via REST API RRS feed

  • Question

  • I notice many sample here http://azurestoragesamples.codeplex.com/ that provides example of using REST API to interacting with Azure Storage.

    In PutBlob sample , I only notice that uploading a file from string such as:

    BlobHelper.PutBlob("samplecontainer1""blob1.txt""This is a text blob!")
    

    What if my file is somewhere stored my local file system now and I want to send it to Azure Storage via REST?

    What I am looking is actually the similar functionality to Blob.UploadFile method. 

    Any advice?

    Friday, January 6, 2012 8:38 AM

Answers

  • Daniell,

    Refer to http://azurestoragesamples.codeplex.com/, do the following changes:

    1.

    Before: public bool PutBlob(string container, string blob, string content)  method

    After: public bool PutBlob(string container, string blob, byte[] content)

    2. Apply this to CreateRESTRequest method:

            public HttpWebRequest CreateRESTRequest(string method, string resource, byte[] data, SortedList<stringstring> headers = null,
                string ifMatch = ""string md5 = "")
            {
                byte[] byteArray = null;
                DateTime now = DateTime.UtcNow;
                string uri = Endpoint + resource;
     
                HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
                request.Method = method;
                request.ContentLength = 0;
                request.Headers.Add("x-ms-date", now.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
                request.Headers.Add("x-ms-version""2009-09-19");
     
                if (IsTableStorage)
                {
                    request.ContentType = "application/atom+xml";
     
                    request.Headers.Add("DataServiceVersion""1.0;NetFx");
                    request.Headers.Add("MaxDataServiceVersion""1.0;NetFx");
                }
     
                if (headers != null)
                {
                    foreach (KeyValuePair<stringstring> header in headers)
                    {
                        request.Headers.Add(header.Key, header.Value);
                    }
                }
                request.ContentLength = data.Length; 
                request.Headers.Add("Authorization", AuthorizationHeader(method, now, request, ifMatch, md5));
     
                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close(); 
     
                return request;
            }

    3. Prepare this method:

            public static byte[] GetBytesFromFile(string fullFilePath)
            {
                FileStream fs = File.OpenRead(fullFilePath);
                try
                {
                    byte[] bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                    fs.Close();
                    return bytes;
                }
                finally
                {
                    fs.Close();
                }
     
            }

    4. To call it:

            static void Main(string[] args)
            {
                BlobHelper BlobHelper = new BlobHelper(StorageAccount, StorageKey);
                byte[] data = GetBytesFromFile("readme.txt");
     
                BlobHelper.PutBlob("samplecontainer1""blob4.txt", data);
            }

    Let me know if it works..


    Regards, Wely Lau http://wely-lau.net (Wordpress on Windows Azure)
    • Marked as answer by Daniell.Chong Tuesday, January 10, 2012 4:29 AM
    Monday, January 9, 2012 9:17 AM

All replies

  • Hi,

      >> What if my file is somewhere stored my local file system now and I want to send it to Azure Storage via REST?

    If you're looking for a CLR wrapper that simplifies working with storage REST services, you can use the built-in storage .NET client library. If you want to learn how to use the REST services, you can use HttpWebRequest directly without any wrapper such as BlobHelper.

    In general, to work with REST services from a .NET client, we can use HttpWebRequest. If you look into the source code of the sample you pointed out, you'll find it also uses this class. In your scenario, please take the following essential steps:
     
    1. Point the request URI to the blob URI.
    2. Set the Method property to "POST".
    3. Populate the necessary request headers.
    4. Call GetRequestStream and populate the request stream using the file content.
    5. Call GetResponse to get the response from the REST service.

     

    Best Regards,

    Ming Xu.


    Please mark the replies as answers if they help or unmark if not.
    If you have any feedback about my replies, please contact msdnmg@microsoft.com.
    Microsoft One Code Framework
    Sunday, January 8, 2012 1:55 PM
  • I did a post showing how to use the REST API to perform various actions with Windows Azure Storage. This also merely uploads a simple string. However, it should be trivial to modify it to get the upload content from a local file. One thing to be aware of is that for a large file you would need to split the file into blocks and use the Put Block operation to upload each block. Then you would need to invoke the Put Block List operation to commit the blocks into the blob.
    Sunday, January 8, 2012 9:16 PM
    Answerer
  • Hi Mingxu and Neil,

    Can you provide any sample code to achieve the upload from file instead of simple string?

    Thanks.

    Monday, January 9, 2012 1:47 AM
  • If you dive into the sample on http://azurestoragesamples.codeplex.com/, you will find your answer. Please also search the web for general usage of HttpWebRequest: http://www.bing.com/search?q=httpwebrequest+sample&src=ie9tr.
    Monday, January 9, 2012 7:57 AM
  • Hi,  http://azurestoragesamples.codeplex.com/ shows how to upload a simple string but doesn't show how to upload a file from local.

    Any assistance is appreciate, please.

    Monday, January 9, 2012 8:48 AM
  • Daniell,

    Refer to http://azurestoragesamples.codeplex.com/, do the following changes:

    1.

    Before: public bool PutBlob(string container, string blob, string content)  method

    After: public bool PutBlob(string container, string blob, byte[] content)

    2. Apply this to CreateRESTRequest method:

            public HttpWebRequest CreateRESTRequest(string method, string resource, byte[] data, SortedList<stringstring> headers = null,
                string ifMatch = ""string md5 = "")
            {
                byte[] byteArray = null;
                DateTime now = DateTime.UtcNow;
                string uri = Endpoint + resource;
     
                HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
                request.Method = method;
                request.ContentLength = 0;
                request.Headers.Add("x-ms-date", now.ToString("R", System.Globalization.CultureInfo.InvariantCulture));
                request.Headers.Add("x-ms-version""2009-09-19");
     
                if (IsTableStorage)
                {
                    request.ContentType = "application/atom+xml";
     
                    request.Headers.Add("DataServiceVersion""1.0;NetFx");
                    request.Headers.Add("MaxDataServiceVersion""1.0;NetFx");
                }
     
                if (headers != null)
                {
                    foreach (KeyValuePair<stringstring> header in headers)
                    {
                        request.Headers.Add(header.Key, header.Value);
                    }
                }
                request.ContentLength = data.Length; 
                request.Headers.Add("Authorization", AuthorizationHeader(method, now, request, ifMatch, md5));
     
                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close(); 
     
                return request;
            }

    3. Prepare this method:

            public static byte[] GetBytesFromFile(string fullFilePath)
            {
                FileStream fs = File.OpenRead(fullFilePath);
                try
                {
                    byte[] bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                    fs.Close();
                    return bytes;
                }
                finally
                {
                    fs.Close();
                }
     
            }

    4. To call it:

            static void Main(string[] args)
            {
                BlobHelper BlobHelper = new BlobHelper(StorageAccount, StorageKey);
                byte[] data = GetBytesFromFile("readme.txt");
     
                BlobHelper.PutBlob("samplecontainer1""blob4.txt", data);
            }

    Let me know if it works..


    Regards, Wely Lau http://wely-lau.net (Wordpress on Windows Azure)
    • Marked as answer by Daniell.Chong Tuesday, January 10, 2012 4:29 AM
    Monday, January 9, 2012 9:17 AM
  • hi wely, it works well. thanks!!!!
    Tuesday, January 10, 2012 4:29 AM