IMG-LOGO

How to download a file using .Net Web API MVC?

andy - 27 Oct, 2017 33153 Views 8 Comment

In this article, you will learn how to download a file in Web API MVC. We will use HTTP Get API method to perform this download action with one single parameter which will accept the file name. Here is the full code.

//import namespaces
using System.IO;
using System.Net.Http.Headers;

[HttpGet]
public HttpResponseMessage DownloadFile(string fileName)
{
	if (!string.IsNullOrEmpty(fileName))
	{
		string filePath = "/images/";
		string fullPath = AppDomain.CurrentDomain.BaseDirectory + filePath + "/" + fileName;
		if (File.Exists(fullPath))
		{

			HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
			var fileStream = new FileStream(fullPath, FileMode.Open);
			response.Content = new StreamContent(fileStream);
			response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
			response.Content.Headers.ContentDisposition.FileName = fileName;
			return response;
		}
	}

	return new HttpResponseMessage(HttpStatusCode.NotFound);
}

So how does the code work? Basically, the API will accept a query string which is the file name. We can get the root path of our project by using the following code.

AppDomain.CurrentDomain.BaseDirectory

What we need to do next is to make sure if the user has passed the file name in the query string and if they are, we then check using System.IO.File to see if the file exists on the server. To test it, you can just need to call the API path in your HTML code. See example below and change the API path accordingly as this is just an example only.

<a href='/APIPath/DownloadFile?fileName=ImageName.jpg'>Download file</a>

Comments

Anurag
18 Jan, 2018
You gotta swap these two lines: response.Content.Headers.ContentDisposition.FileName = fileName; response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); Initialize content disposition first and then set file name.
andy
18 Jan, 2018
Hi Anurag, Thanks for correcting the codes. I have updated as advised.
Stamatis
05 Apr, 2018
Very good tutorial. It works with very efficiently written code. Thank you very much for this!
Bhavesh Parmar
28 Jun, 2018
Hey!! I was faced trouble when i publish the web api and i was got error- 500 internal server error please give me suggestion
andy
28 Jun, 2018
Hi Bhavesh, Would you be able to turn off the customErrors mode to OFF in web.config file? It should tell you more details about what is the error.
mike
09 Aug, 2018
Worked great out of the box...thanks so much!
Vaishali
10 Apr, 2020
Thank You... How to download file from database (In database file is save binary format) how to get this file and download using mvc5 web api... you write this type of API please share..
Vignesh
24 Jun, 2020
Thank you.. It's an helpful information.
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

ASP.Net MVC Identity without Entity Framework

Learn how to create your own custom identity authentication and authorization with ASP Net MVC without using Entity Framework By default the example given in the MVC official tutorial site is using Entity Framework So if you do not want ...

How to enable attribute routing in C# MVC?

p If you want to enable routing in C MVC you have to do the following steps Note this only applies to strong MVC version 5 or above strong Open your RouteConfig cs file under App_Start folder in your MVC ...

PayPal Express Checkout using C# MVC Web API

p In this tutorial you will learn how easily you can implement a simple checkout express using C MVC Web API We will create a really simple shopping cart where customers can add and delete their cart items before proceed ...