locked
File Download Not Working From Ajax Call RRS feed

  • Question

  • User1349647816 posted

    I have an ajax call on my frontend that calls a c# function on the back end to download a pdf document, the psd document is located in the documents folder within the application. I am using the "HttpResponse" to download the file but it just isn't working, I think that the ajax call may be preventing this somehow, can someone please advise here is the code snippet from my c# function

    FileInfo file = new FileInfo(outputFile);
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.ContentType = "application/pdf";
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(outputFile));
    HttpContext.Current.Response.TransmitFile(outputFile);
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.End();

    Thursday, November 5, 2020 10:38 AM

All replies

  • User753101303 posted

    Hi,

    As for all Ajax queries, the browser won"t do anything with the response which is instead exposed programmatically by the Ajax API you are using..

    If instead you don't use Ajax the browser will process the response (as for all non Ajax queries) and based on headers will see that it should show a download dialog rather than to replace the current window content which should be left unchanged.

    If for some reason you really want to use Ajax , see for example https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax and scroll down a bit: the usual approach is to create and click programmatically a download link, the content being copied to a data url. 

    Thursday, November 5, 2020 12:47 PM