Download an excel file in JQuery-AJAX request from ASP.NET MVC

不羁岁月 提交于 2019-12-19 04:19:26

问题


In my ASP.NET MVC project, I generated a excel file using ClosedXML.

It works well in non-ajax call. Here is my controller action method

 // Prepare the response
 Response.Clear();
 Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
 Response.AddHeader("content-disposition", "attachment;filename=\"" + reportHeader + ".xlsx\"");

 // Flush the workbook to the Response.OutputStream
 using (MemoryStream memoryStream = new MemoryStream())
 {
     MyWorkBook.SaveAs(memoryStream);
     memoryStream.WriteTo(Response.OutputStream);
     memoryStream.Close();
 }
 Response.End();

Now I am trying to do it via an ajax request. But the file is not sent from mvc controller.

$.ajax({
                url: url,
                type: "POST",
                data: fd,
                processData: false,  
                contentType: false,  
                beforeSend: function () {
                },
                success: function (response) {

                },
                error: function (request, status, error) {
                },
                complete: function () {
                }
            });

How can i accomplish it? Thank you in advance.


回答1:


Why not? ramiramilu was right about using window.location and iframe. I did the same thing but for ASP.NET MVC3.

I would suggest to use controller which returns FileContentResult

FYI about FileContentResult MSDN

And finally how I did it (Controller):

    [HttpPost]
    public HttpStatusCodeResult CreateExcel()
    {
        XLWorkbook wb = new XLWorkbook(XLEventTracking.Disabled); //create Excel

        //Generate information for excel file
        // ...

        if (wb != null)
        {
            Session["ExcelResult"] = wb;
            return new HttpStatusCodeResult(HttpStatusCode.OK);
        }

        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

    }

    [HttpGet]
    public FileContentResult ExcelResult(string reportHeader) //it's your data passed to controller
    {

        byte[] fileBytes = GetExcel((XLWorkbook)Session["ExcelResult"]);
        return File(fileBytes, MediaTypeNames.Application.Octet, reportHeader + ".xlsx");
    }

In model (you can remove static if you wish, and call it with instance)

public static byte[] GetExcel(XLWorkbook wb)
{
    using (var ms = new MemoryStream())
    {
        wb.SaveAs(ms);
        return ms.ToArray();
    }
}

AJAX:

$.ajax({
            url: "@Url.Action("CreateExcel")",
            async: true,
            type: "POST",
            traditional: true,
            cache: false,
            statusCode: {
                400: function () {
                    alert("Sorry! We cannot process you request");
                },
                200: function () {
                    $("#fileHolder")
                    .attr('src', 
                    '@Url.Action("ExcelResult")?reportHeader=' + 
                    reportHeader);
                }
            }
        });

BTW, I removed all exception handlers to simplify the code, but I assume You can do it yourself.




回答2:


You cannot DIRECTLY download a file using AJAX, but you can download a file using window.location in conjunction with AJAX to make the file downloaded. What I mean is that if you use AJAX GET/POST all the file content will be in memory of the browser but cannot be saved to disk (because of JavaScript limitations).

Instead you can use window.location to point to a URL which in turn will fetch the file and prompt the save/open prompt. Or else you can use a hidden iFrame and set the src attribute of iFrame with the URL from which will download the file.



来源:https://stackoverflow.com/questions/27874360/download-an-excel-file-in-jquery-ajax-request-from-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!