:::: MENU ::::

File upload in ASP.NET Core web API

In this post, I will show how to upload a file in ASP.NET Core API and store it in Azure storage as a blob.

To accept file you can use IFormFile type object. Based on your requirement you can use IFormFile or ICollection<IFormFile> type as a parameter for API action. IFormFile exposes properties like FileName, Name, ContentDisposition, Length and other many more useful properties and methods.


Tips: If you are customizing your API controller consumes content-type then don’t forget to add multipart/form-data content type as one of the consumes type.

Now, lets use postman to test our API.

Change input type to file as shown by right arrow and input parameter name (key) same as our action parameter name in left. Now choose a file from the location shown by the middle arrow and send the request.

Woo! File is successfully uploaded in our API. You can see the file name and we read file as a stream. Now let’s save this file in Azure blob storage.

First, you need to include a required library of windows storage in project.json.

Tips: You need to change/add framework type to make it work (if you haven’t earlier). More details on why you need to change target framework see here.

Library to add in project.json. “7.1.3-preview” is the latest version of this library by the time this post is written.

Changes in the framework:

Now let’s write some code to upload a file.

First get the connection string of your azure storage account and then get the reference of blob container. In my case I have created a container, name as profileimages and lastly, I am uploading a file (file stream to be more specific). Here you can play with the result of UploadFromStreamAsync method to return any status or URI of the file after file is uploaded. But for simplicity I used blob details hold by CloudBlockBlob object and return file URI. Before returning file URI don’t forget to dispose stream object.

That’s it. The file is uploaded in Azure Storage and you got blob (file) URI now you can return URI to the client as API response.

That’s it this is how you can upload a file in ASP.NET core web API and store it in Azure Storage.

Happy Coding 🙂