file download by calling .ashx page

I’m requesting .ashx page from Master page client side script (Jquery) which has a code to download a PDF file. When I debug it, I can see the execution of “file download” code but file is not downloading.

$.ajax({
    type: "POST",
    url: "FileDownload.ashx",
    dataType: "html",
    success: function (data) { }
} );

public class FileDownload : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");

        string fileName = "BUSProjectCard.pdf";
        string filePath = context.Server.MapPath("~/Print/");
        context.Response.Clear();
        context.Response.ContentType = "application/pdf";
        context.Response.AddHeader("Content-Disposition", "attachment; filename="+fileName);
        context.Response.TransmitFile(filePath + fileName);
        context.Response.End();
    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Your file is downloading, but you get it on javascript, on the data parameter of your call because you call it with Ajax.

You use a handler – so ajax not needed here, and the most easy thing to do using javascript is that:

window.location = "FileDownload.ashx?parametres=22";

or with a simple link as
  <a target="_blank" href="FileDownload.ashx?parametres=22" rel="nofollow noreferrer noopener" >download...</a>

Ah, and send the parameters via the url, you can not post them that way.

You can also read: What is the best way to download file from server


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x