简体   繁体   中英

Download Excel file via AJAX MVC without saving the file on server in ASP.Net/C#

I read Luchian's suggestion on this link

Download Excel file via AJAX MVC

and I do like his idea very much that way I can avoid potentially saving 2 copies of the spreadsheet. Or having to worry about deleting the initial file that gets saved on the server before the AJAX call returns.

So if I save the spreadsheet as a memorystream and insert it into a unique Cache variable say cache_uniq1 and return that on the AJAX call, how would I then open the stream?

Can I just do window.open?

$.ajax({    
    type: 'POST',    
    url: '/Reports/Somepage.aspx',     
    data: '{ "dataprop1": "test", "dataprop2" : "test2" }',    
    //contentType: 'application/json; charset=utf-8',    
    //dataType: 'json',    
    success: function (returnValue) {   

        //window.location = /Reports/Download?file=' + returnValue;    
        //    
        //NOTE: Instead the returnValue = cache_uniq1 which is the unique Cache     
        //variable name that holds the Excel spreadsheet as a memory stream
    }
});

Any help is greatly appreciated. FYI my application is a straight on ASP.Net Web site (not using MVC).

    [OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)]
    [Authorize]
    public ActionResult DownloadExportedFile(string filename = null)
    {
        if (!String.IsNullOrEmpty(filename))
        {
            var tempDirPath = System.IO.Path.GetTempPath();

            if (System.IO.File.Exists(tempDirPath + filename))
            {
                var bytes = System.IO.File.ReadAllBytes(tempDirPath + filename);

                System.IO.File.Delete(tempDirPath + filename);

                var cd = new System.Net.Mime.ContentDisposition
                {
                    FileName = Path.GetFileName("BookingForm.csv"),

                    // always prompt the user for downloading, set to true if you want 
                    // the browser to try to show the file inline
                    Inline = false
                };

                //Response.AppendHeader("Content-Disposition", cd.ToString());

                return File(bytes, "text/csv", "BookingForm.csv");
            }
        }

        return new HttpStatusCodeResult(404, "File not found!");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM