In this post let’s see how we can directly upload files to Amazon S3 which are sent through ASP.NET Web API service via a form object by client side. The nice thing here is we are not going to save the files locally while the upload is happening. File will be directly uploaded to Amazon S3.
Let’s go by a example. My client application is an AngularJS application. Here I am not going to write about how to consume ASP.NET Web API services from AngularJS application. Sometimes back I wrote an article about AngularJS Consuming ASP.NET Web API RESTful Services, you can refer that post for more information on AngularJS consuming ASP.NET Web API services.
I have modified the sample in AngularJS Consuming ASP.NET Web API RESTful Services post to send a POST request to ASP.NET Web API service, and the request contains the form object which contains the file to upload.
Here is my view template file. I have a file-select field to open the folder browser.
In my AngularJS Controller, I have the following.
If you are not familiar with AngularJS, you can just ignore the above part. Here basically what I have done is sending a POST request to my ASP.NET Web API service including the file I need to upload and some additional data.
Now let’s move into my ASP.NET Web API project. There I have a API Controller named “EmployeesController” and there I have a action named “Upload”.
In here first I am checking whether the requests’ content is MIME multipart content. If yes, I am reading all body parts within a MIME multipart message and produces a result of type InMemoryMultipartStreamProvider. In here InMemoryMultipartStreamProvider is my implementation of abstract class MultipartStreamProvider. There I have overrided the GetStream method just to return me a MemoryStream. The implementation of it is totally based on MultipartFormDataStreamProvider and MultipartFileStreamProvider. The MultipartFormDataStreamProvider has two constructors, one taking a root path and other taking root path and a buffer size. If you look at the implementation of MultipartFormDataStreamProvider, inside the GetStream method the files are saving locally. Here in my implementation I have removed them, as I don’t want that to happen.
After getting the stream of the file, I have a helper class named “StorageService”, which is used to upload the file into Amazon S3. Amazon S3 SDK for .NET can upload files via a stream. After uploading is completed, I am returning the uploaded files’ Url.
Now when I run the project, I am getting the following. When I click on the choose file button, folder explorer opens and I can select a image file there.