9

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();
    }
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
dotnetrocks
  • 2,589
  • 12
  • 36
  • 55

1 Answers1

15

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" >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

Community
  • 1
  • 1
Aristos
  • 66,005
  • 16
  • 114
  • 150
  • This is very helpfull, you are right with the answer. After few minutes trying to download a file in .ashx with a json call in the client, I didn't get the file in any way. – amelian Oct 21 '14 at 10:30
  • @Aristos this works perfectly. But I need to show the message if something goes wrong at the server side.. How would I do that? Messages "Something went wrong or File Not found" – Praburaj Feb 24 '17 at 13:22
  • @Prabu at the server side you only can log the error - relative easy inside the handler. Find or write a log class... – Aristos Feb 24 '17 at 18:10
  • 1
    @Aristos But I need inform the client if something goes wrong – Praburaj Feb 27 '17 at 10:17