Dhanil Dinesan
Dhanil Dinesan

Reputation: 575

How to download excel file using Ajax method- here my file is downloaded in Temp folder not Downloaded in Browser?

I want to download an excel file. I'm using ajax method to get the file but it's not working for me. My file is downloaded into a temp folder but it's not downloading in the browser.

c# and jquery

jquery

//Exporting errors to excel file
function ExcportErrorListToExcel() {
    debugger;
    $.ajax({
        url: 'Import/ExportErrorToExcel',
        type: 'GET',
        data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },       
        //contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        success: function (returnValue) {
            debugger;       
            window.location = '/Import/ExportErrorToExcel?file=' + returnValue.filename;
            //alert('success');
        }
    });
}

controller

#region ExportErrorToExcel        
        public ActionResult ExportErrorToExcel(string dataExchangeSelectedColum, string entityvalue, string filename)
        {
            UA patsUA = Session["PaTSUA"] as UA;
            DataTable dataTable = null;
            dataTable = _dataExchangeBusiness.DataValidation(dataExchangeSelectedColum, entityvalue, filename, patsUA.DBConnectionString);

            string tempPath = Server.MapPath("~/Temp/" + Guid.NewGuid().ToString() + ".xlsx");


          _dataExchangeBusiness.ExportErrorToExcel(dataTable,tempPath, entityvalue);

            FileInfo fileInfo = new FileInfo(tempPath);
            if (fileInfo.Exists)
            {
                Response.Clear();
                byte[] excelBytes = System.IO.File.ReadAllBytes(tempPath);

                MemoryStream memoryStream = new MemoryStream(excelBytes);
                Response.ContentType= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=ErrorList.xlsx");
                Response.Buffer = true;
                memoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.End();
                //System.IO.File.Delete(tempPath);
            }

            //var errorRowList = (from e in dataTable.AsEnumerable()
            //                             where e.Field<string>("DataError").ToString() != ""
            //                             select e).ToList();

            return File(tempPath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Path.GetFileName(tempPath));
            //return Json(new { Status = "OK", Records = tempPath, contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
        }
        #endregion ExportErrorToExcel

Upvotes: 1

Views: 2791

Answers (2)

Dhanil Dinesan
Dhanil Dinesan

Reputation: 575

This can be simply done by split that controller function into two.The first function will save the file in a temp folder and pass the file name to the jquery Ajax function and in its success section it will redirected to the second function in the controller.Here we will Download the file

Here is the Ajax

    function ExportErrorListToExcel() {
    debugger;
    $.ajax({
        url: "Import/ExportErrorToExcel",
        type: "POST",
        data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },       
        success: function (responsetext, status, xhr) {
            debugger;
            window.location = 'Import/DownloadErrorData?fname=' + responsetext.FileName;
        }
    });
   // $('#ExcelExportForm').submit();
}

Here is the Controller function where the file is saved into a temp folder

#region ExportErrorToExcel
    //This function will return the file name to script
    public ActionResult ExportErrorToExcel(string dataExchangeSelectedColum, string entityvalue, string filename)
    {

        UA patsUA = Session["PaTSUA"] as UA;
        DataTable dataTable = null;
        dataTable = _dataExchangeBusiness.DataValidation(dataExchangeSelectedColum, entityvalue, filename, patsUA.DBConnectionString);

        string tempPath = Server.MapPath("~/Temp/" + Guid.NewGuid().ToString()+ ".xlsx");            

        _dataExchangeBusiness.ExportErrorToExcel(dataTable,tempPath, entityvalue);
        string fname = Path.GetFileName(tempPath);

        return Json(new { Result = "true", Message = "Success", FileName = fname,Entity=entityvalue });
    }
    #endregion ExportErrorToExcel

Here is the controller 2nd function for download the file from Temp folder

#region DownloadErrorData

    //In this function recieve the filename and will download it from the location
    public ActionResult DownloadErrorData(string fname)
    {
        string fileName ="ErrorList.xlsx";
        string filePath= Path.Combine(Server.MapPath("~/Temp/" + fname));
        try
        {
            string[] allFiles = Directory.GetFiles(Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar);
            foreach (string file in allFiles)
            {
                FileInfo fileinfo = new FileInfo(file);
                if (fileinfo.CreationTime < DateTime.Now.AddDays(-2))
                {
                    fileinfo.Delete();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";//web content type of .xlsx files
        return File(filePath, contentType, fileName);
    }
    #endregion DownloadErrorData

Hope this will help for someone :)

Upvotes: 1

Udara Kasun
Udara Kasun

Reputation: 2216

Try this

//Exporting errors to excel file
function ExcportErrorListToExcel() {
    debugger;
    $.ajax({
        url: 'Import/ExportErrorToExcel',
        type: 'GET',
        data: { dataExchangeSelectedColum: $('#hdnSelectedColumn').val(), entityvalue: $('#hdnEntity').val(), filename: $('#hdnFileName').val() },       
        //contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        success: function (returnValue) {
            debugger;  
            var link=document.createElement('a');
            document.body.appendChild(link);
            link.href="/Temp/" + returnValue.filename;
            link.click();
            link.remove();
        }
    });
}

Upvotes: 2

Related Questions