Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery and Ajax to save a file in ASP.Net

I have a button that uses jQuery and ajax to call a server side script to create a text file and sends back the following response:

Response.ContentType = "csv";
Response.AddHeader("Content-disposition", "attachment; filename=" + fName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(btFile);
Response.End();

However, the save dialog does not appear. If I don't use ajax and perform a full postback with the same code, it works. Any ideas?

Here is the jQuery code:

$(function() {
    $('#reportButton').click(function() {
        $.ajax({
            type: "POST",
            url: "GenerateReport.aspx",
            data: "id=0",
            success: function(){
            }
        });
    });
});
like image 536
Arizona1911 Avatar asked Jun 24 '10 16:06

Arizona1911


People also ask

Can we download file using Ajax?

The file will be downloaded as BLOB using jQuery AJAX and XmlHttpRequest (XHR) request and then the file will be downloaded using the Response inside the Success event handler of jQuery AJAX function. In this article I will explain with an example, how to download file in AJAX Response (Success) using jQuery.

How can I download Excel file using jQuery?

Downloading Excel File using AJAX in jQueryInside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).


2 Answers

Rather than using AJAX (which will not work, as Brian mentions), you can fake it by using jQuery to dynamically create a form and an iframe to post it to. Here is an example I found -- you should read through the comments for some improvements (like the use of a dynamically created iframe to prevent problems if your page does not return the proper headers).

like image 69
patmortech Avatar answered Sep 19 '22 02:09

patmortech


I think the issue is the AJAX, and if the request was made as a standard request outside JQuery, you would get the save dialog box. JQuery requests would stream the data to the callback...

like image 25
Brian Mains Avatar answered Sep 20 '22 02:09

Brian Mains