Click here to Skip to main content
15,879,095 members
Articles / Web Development / ASP.NET
Tip/Trick

How to Create and Download File with Ajax in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
5.00/5 (10 votes)
17 Nov 2016CPOL 145.6K   12   11
Create and download the file with Ajax call in ASP.NET MVC

Introduction

When you use the Ajax call in ASP.NET MVC, you can just return a JSON object but not a file. If you want to do that, you need to create and save the file in server and return its path to Ajax.

After that, you can call a redirect link for downloading the file, because this is a temp file, so you should need to delete it after download.

Using the Code

The below demo code is just for creating and downloading an Excel file:

  1. Create an Action for generating the Excel:
    C#
    [HttpPost]
    public JsonResult ExportExcel()
    {
        DataTable dt = DataService.GetData();
        var fileName = "Excel_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls";
        
        //save the file to server temp folder
        string fullPath = Path.Combine(Server.MapPath("~/temp"), fileName);
    
        using (var exportData = new MemoryStream())
        {
            //I don't show the detail how to create the Excel, this is not the point of this article,
            //I just use the NPOI for Excel handler
            Utility.WriteDataTableToExcel(dt, ".xls", exportData);
    
            FileStream file = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
            exportData.WriteTo(file);
            file.Close();
        }
    
        var errorMessage = "you can return the errors in here!";
    
        //return the Excel file name
        return Json(new { fileName = fileName, errorMessage = "" });
    }
  2. Create the download Action:
    C#
    [HttpGet]
    [DeleteFileAttribute] //Action Filter, it will auto delete the file after download, 
                          //I will explain it later
    public ActionResult Download(string file)
    {
        //get the temp folder and file path in server
        string fullPath = Path.Combine(Server.MapPath("~/temp"), file);
    
        //return the file for download, this is an Excel 
        //so I set the file content type to "application/vnd.ms-excel"
        return File(fullPath, "application/vnd.ms-excel", file);
    }
  3. We need to auto delete the file after download, so we need to create an Action Filter:
    C#
    public class DeleteFileAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.HttpContext.Response.Flush();
    
            //convert the current filter context to file and get the file path
            string filePath = (filterContext.Result as FilePathResult).FileName;
            
            //delete the file after download
            System.IO.File.Delete(filePath);
        }
    }
  4. Use the Ajax call in frontend:
    JavaScript
    //I use blockUI for loading...
    $.blockUI({ message: '<h3>Please wait a moment...</h3>' });    
    $.ajax({
        type: "POST",
        url: '@Url.Action("ExportExcel","YourController")', //call your controller and action
        contentType: "application/json; charset=utf-8",
        dataType: "json",
    }).done(function (data) {
        //console.log(data.result);
        $.unblockUI();
    
        //get the file name for download
        if (data.fileName != "") {
            //use window.location.href for redirect to download action for download the file
            window.location.href = "@Url.RouteUrl(new 
                { Controller = "YourController", Action = "Download"})/?file=" + data.fileName;
        }
    });

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Hong Kong Hong Kong
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionVery nice with example thanks Pin
metkar4-Oct-22 7:56
metkar4-Oct-22 7:56 
GeneralMy vote of 5 Pin
Mike_Finch18-Jun-21 12:53
Mike_Finch18-Jun-21 12:53 
GeneralRe: My vote of 5 Pin
Winson Yau25-Aug-21 2:47
Winson Yau25-Aug-21 2:47 
QuestionCan u please share the code of "Utility.WriteDataTableToExcel" function Pin
Member 1032029310-Jul-18 20:31
Member 1032029310-Jul-18 20:31 
QuestionCan u please share the code of "Utility.WriteDataTableToExcel" function Pin
sarfraz4095-Jul-18 21:47
sarfraz4095-Jul-18 21:47 
QuestionThanks Pin
Majid Qafouri22-Jan-18 22:27
Majid Qafouri22-Jan-18 22:27 
QuestionAwesome work!!! Pin
Ghouse M1-Jan-18 7:42
Ghouse M1-Jan-18 7:42 
QuestionThanks from Argentina Pin
MarceloGuy30-Sep-17 7:25
MarceloGuy30-Sep-17 7:25 
AnswerRe: Thanks from Argentina Pin
Winson Yau29-Nov-17 14:54
Winson Yau29-Nov-17 14:54 
you are welcome Smile | :)
GeneralThank Pin
Elvin Acevedo30-Jun-17 9:14
Elvin Acevedo30-Jun-17 9:14 
GeneralRe: Thank Pin
Winson Yau20-Jul-17 5:46
Winson Yau20-Jul-17 5:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.