Published on: 21 February, 2016

How to trigger a download file in c# MVC controller?

Tumblr Digg Google Plus

you want to know how you can easily trigger a popup download in MVC controller rather than using a href link to open into a new window?

Below is the simple script on how you can do it.

public FileContentResult Download(long listingID) {
	var document = new FileInfo(Server.MapPath("~/sample.pdf"));
	if (document != null) {
		Response.AppendHeader("Content-Disposition", "FileName=sample.pdf");
		return File(System.IO.File.ReadAllBytes(filepath), "application/octet-stream");
	}
	return null;
}

Comments

John A Davis
03 April, 2017
How do I call FileContentResult. I tried like this but got an error (I took out the (long listingID) and used a hardcoded path to a .jpg): @Html.ActionLink("Download your pictures", "FileContentResult", "Home"); I got this error: The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. Requested URL: /Home/FileContentResult
andy
03 April, 2017
Could you confirm if the path is correct? If you want to use FileContentResult, you can use something like this. byte[] content = your_byte[]; FileContentResult result = new FileContentResult(content, "application/octet-stream") { FileDownloadName = "file_name"; }; return result;
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.