In this article, I will show you download file to client browser from a server using asp.net c# MVC razor view with example. I am using FileResult, it allows user to download file from the folder with specified file name. It will return the file with generic octet-stream MIME type.
When the user clicks the download button, it requests the controller method and the specified PDF file will be downloaded by the client browser.
Step 1: Create a mvc application and Right click on the controller folder and add name “Home”. Copy and paste the following code.
public class HomeController : Controller
{
//
public ActionResult Index()
{
return View();
}
private string filePath = "~/Files/";
public FileResult DownloadFile()
{
var sDocument = Server.MapPath(filePath + "newFile.pdf");
byte[] fileBytes = System.IO.File.ReadAllBytes(sDocument);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, sDocument);
}
}
Step 2: Right click on the homeController and create an index view. Copy and paste the following code.
<h2>Download a File with MVC4 Razor view</h2>
<span class="label"><b>Information:</b></span>
@using (Html.BeginForm("DownloadFile", "Download", FormMethod.Get))
{
<input type="submit" value="Download" />
}
Post your comments / questions
Recent Article
- How to fix HAXM is not installed |in Android Studio
- How to fix CMOS Checksum Error in Computer or Laptop | SOLVED
- Reactivating windows after a Hardware change on PC or Laptop
- FIXED: Windows reported that the hardware of your device has changed. Error code :0xc004F211
- "redirect" is not defined pylance("reportUndefinedVariable)
- This action cannot be completed because the file is open in SQL Server(SQLEXPRESS) - FIXED
- Unicode error 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape
- Could not find the 'angular-devkit/build-angular:dev-server' builder's node package | Angular Error
Related Article