Handling FileResult from jQuery Ajax

I have a C # MVC 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 do not want it to open in the browser) I call the controller via the $ .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 to process data to make it load?

+6
source share
1 answer

You will not be able to use JavaScript to save the file to disk, because it is locked for security reasons.

An alternative would be to save the file in the FinaliseQuote action FinaliseQuote (and return only the file identifier), and then create another action method that responds to the GET request and returns the file. In your success function, you set window.location.href to point to a new action method (you need to pass the file identifier). Also make sure that the MIME type is set to application/octet-stream and this will 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; }, 
+5
source

Source: https://habr.com/ru/post/988559/


All Articles