4
I am using this method to return a PDF file. It works normal if I call this action directly via URL:
    public ActionResult GerarProva(int idEpo, int numero, bool existeProvaGerada)
    {
        try
        {
            var relatorioBll = new RelatorioBll();
            var dados = relatorioBll.ObterQuestoesProva(numero, idEpo, existeProvaGerada);
            _dadosGeracaoProva = dados;
            System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
            System.Web.HttpContext.Current.Response.AddHeader("content-disposition",
                "attachment;filename=" + ControllerContext.RouteData.Values["action"] + DateTime.Now.ToFileTime() +
                ".pdf");
            System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Stream pdfStream = System.Web.HttpContext.Current.Response.OutputStream;
            GerarPdf<ProvaItem>.GerarProva(pdfStream, dados.ToList());
            System.Web.HttpContext.Current.Response.Write(dados);
            System.Web.HttpContext.Current.Response.End();
            return File(System.Web.HttpContext.Current.Response.OutputStream, "application/pdf");
        }
        catch (Exception ex)
        {
            Danger("Erro: " + ex.Message);
        }
        return RedirectToAction("Index");
    }
But I would like to download the file through ajax. Because I need to perform a javascript action within "Success":
            $.ajax({
                url: link,
                success: function (data) {
                    var blob = new Blob([data]);
                    var link = document.createElement('a');
                    link.href = window.URL.createObjectURL(blob);
                    link.download = "Preview.pdf";
                    link.click();
                },
                error: function (err, er, e) {
                    if (err.responseText.indexOf("encontradas") === -1) {
                        alert("Erro.");
                    } else {
                        alert("Erro: Não foram encontradas questões válidas para a geração da prova.");
                    }
                }
            });
I tried this code, but the pdf comes with the blank pages. An assumption of mine is that my server side method is not returning the correct type...
Actually this is a gambiarra. Ajax does not return file. The correct one would be to use a normal link to download.
– Leonel Sanches da Silva
I was using a normal link. However I need to perform a javascript action at the end of the download.
– Joao Paulo
So this is not the way. It’s right for you to wait for the post-download action.
– Leonel Sanches da Silva
When I click on the link and the pdf is downloaded I have no way to do the action I wanted via javascript. So I thought of this alternative
– Joao Paulo
according to this other gambiarra, you can create a cookie on the client and invalidate it on the server side after the download is completed.
– Tobias Mesquita
more details: http://dejanstojanovic.net/jquery-javascript/2015/march/detect-when-file-download-request-is-finished-with-jquery/
– Tobias Mesquita
Try making the ajax call synchronous. It is asynchronous by default, and this may be causing some problem. I had a similar problem when using an autocomplete plugin (the search method was server-side, called via ajax), and only managed to solve it that way. To make the call synchronous, add the following parameter:
async: false,– drigomed