Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling FileResult from JQuery Ajax

I have a MVC C# Controller that returns a FileResult

    [HttpPost]
    public FileResult FinaliseQuote(string quote)
    {
        var finalisedQuote = JsonConvert.DeserializeObject<FinalisedQuote>(System.Uri.UnescapeDataString(quote));

        return File(finalisedQuote.ConvertToPdf(), "application/pdf");
    }

Now I want to be able to download the result (I don't want it to open up in the browser) I am calling the controller via $.ajax method in JavaScript

var postData = { quote: finalisedQuote };

var url = "/NewQuote/FinaliseQuote";

$.ajax({
    type: "POST",
    url: url,
    data: postData,
    success: function (data) {
        //how do I handle data to force download
    },
    fail: function (msg) {
        alert(msg)
    },
    datatype: "json"
});

How do I handle the data to force it to download?

like image 203
Michael Avatar asked Jun 05 '15 08:06

Michael


1 Answers

You won't be able to use JavaScript to save the file to disk as this is blocked for security reasons.

An alternative would be to save the file in the FinaliseQuote action method (and return just an id for the file), then create another action method that responds to a GET request and returns the file. In your success function you then set window.location.href to point to your new action method (you'll need to pass an id for the file). Also make sure you set the MIME type to application/octet-stream and that should force the browser to download the file.

Controller:

[HttpPost]
public JsonResult FinaliseQuote(string quote)
{
    var finalisedQuote = JsonConvert.DeserializeObject<FinalisedQuote>(System.Uri.UnescapeDataString(quote));

    // save the file and return an id...
}

public FileResult DownloadFile(int id)
{
    var fs = System.IO.File.OpenRead(Server.MapPath(string.Format("~/Content/file{0}.pdf", id)));

    // this is needed for IE to save the file instead of opening it
    HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=\"filename\""); 

    return File(fs, "application/octet-stream");
}

JS:

success: function (data) {
    window.location.href = "/NewQuote/DownloadFile?id=" + data;
},
like image 127
Lee Bailey Avatar answered Sep 20 '22 06:09

Lee Bailey