简体   繁体   中英

MVC download file through AJAX POST

I want to allow users to choose a file to download from a drop down list. Once they have made a selection, they can click the download button. However, the file does not download correctly.

Here is the controller for generating and returning the file:

[HttpPost]
    public ActionResult DownloadReport(int? id, string templateChoice)
    {
        if (id == null)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        try
        {
            byte[] file = GetReport(id, templateChoice);
            return File(file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ResumeReport.docx");
        }
        catch (InvalidOperationException)
        {
            return View();
        }
    }

The JavaScript function which is called upon pressing the generate report button is:

function downloadReport(InputID) {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("DownloadReport", "UserProfiles")',
            data: JSON.stringify({ "ID": InputID, "TemplateChoice": $("#resumeTemplates").val() }),
            contentType: 'application/json; charset=utf-8'
        });
    }

Opening the inspect window in chrome and going to the network tab shows the document data is received, but it does not download like a regular file.

I seemed to have found a working solution which does not reload page, does not redirect the user, and does not show any excess text in the URL upon pressing the download button. I replaced my current JavaScript function with the following:

function downloadReport(inputID) {
        window.location.href = '/UserProfiles/DownloadReport/?id=' + inputID + '&template=' + $('#resumeTemplates').val();
    }

And my controller now looks like:

public ActionResult DownloadReport(int? id, string template)
    {
        if (id == null || template == null)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        try
        {
            byte[] file = GetReport(id, template);
            return File(file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ResumeReport.docx");
        }
        catch (InvalidOperationException)
        {
            return View();
        }
    }

I also added this into my RouteConfig.cs file:

routes.MapRoute(
            "DownloadReport",
            "{controller}/{action}/{id}/{template}",
            new { controller = "UserProfiles", action = "DownloadReport", id = UrlParameter.Optional, template = UrlParameter.Optional }
        );

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