Coding Geek

A blog by Nadeem Iqbal

June 2009 - Posts

Upload file Directly to Amazon S3 using C# via POST

There are scenarios when you want to directly upload the file from the client browser/application to S3.

Amazon provides simple POST method to upload files to amazon File Upload. That method is not acceptable when you want to upload the file(s) programatically using any programming language such as C# or by using the Silverlight.

C# doesn't provide the support of  "multipart/form-data" form posting which is required to upload directly to the S3. So, HttpWebRequest class can be configured so that it will send the request in the required format.

 So, I've written a custom class which will generate the request contents in "multipart/form-data" format.

Below is the code how to use that custom class and upload to the amazon S3 directly using C#/SilverLight

UploadFile uf = new UploadFile("file.txt", "file", "txt/html"); // file should be in bin directory
            string []a = new string[5];
            UploadFile[] files = new UploadFile[1];
            files[0] = uf;

            NameValueCollection form = new NameValueCollection();
            form["key"] = "file.txt";
            form["acl"] = "public-read";
            form["success_action_redirect"] = "http://www.yahoo.com";
           
            form["x-amz-meta-uuid"] = "14365123651274";
            form["x-amz-meta-tag"] = "";
            form["AWSAccessKeyId"] = "zzzzzzzz";
            form["Policy"] = "zzzzzzzzzzzzzzzzzzzzzzzz";
            form["Signature"] = "zzzzzzzzzzzzzzzzzzzzzzzzz";
           
            
            string url = "http://MyBucket.s3.amazonaws.com/";

            string resultQuery = HttpUploadHelper.Upload(url, files, form);
            Console.WriteLine(resultQuery);
 

CHEERS :)
More Posts