:::: MENU ::::

File upload in ASP.NET Core web API

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

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

Implementation:

Tips: If you are customizing your API controller consumes content-type then don’t forgot 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 file from the location shown by middle arrow and send the request.

Woo! File is successfully uploaded in our API. You can see file name and we read file as stream. Now lets save this file in azure blob storage.

First you need to include 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 latest version of this library by the time this post is written.

Changes in framework:

Now let’s write some code to upload 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 container, name as profileimages and lastly I am uploading file (file stream to be more specific). Here you can play with result of UploadFromStreamAsync method to return any status or URI of 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 forgot to dispose stream object.

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

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

Happy Coding 🙂