Click here to Skip to main content
14,691,047 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:

From Jquery ajax i am making a C# function call which is returing a file download option.

If i am using $.ajax, it is not working, if i am giving window.location = url then that download box is coming.

I am trying to download one excel file.

I have given this content type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.
I am making that C# response object property OutputStream write to memorystream object.

Please let me know if i missed anything.
Updated 14-Mar-12 22:00pm
ZurdoDev 14-Mar-12 7:55am
So, what is the question? It works when you set window.location but you want to use .ajax? Show your .ajax code.
Dhaval__Patel 14-Mar-12 9:36am
paste some code so we can understand how ur calling c# from ajax .. it will help
Member 7217874 15-Mar-12 4:24am
url: controllerUrl,
type: 'Get',
// datatype: "text",
contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
// contentType: "text/plain; charset=UTF-8",
beforeSend: function (xhr) {
xhr.overrideMimeType('text/plain; charset=UTF-8')
$(that.el).parent().block({ message: "Processing..." });
// window.location = controllerUrl;
success: function (data) {

complete: function (data) {
error: function (jqXHR,textStatus) {

1 solution

If I understand your question correctly you can't actually perform a file download with Ajax directly. You can request a file using Ajax but your Ajax response will contain the actual bits for the file. Due to JavaScript security limitations you won't be able to save those bits onto the user's computer with a file download dialog. For more information on why this is take a look at my blog post here

I created the Query File Download plugin (Demo) which fixes the problem and provides some other nice features. It basically gives you a "full Ajax-like" experience for file downloads (complete with callbacks even) that isn't normally possible for file downloads. It also has some other handy features:

- User never leaves the same page they initiated a file download from whether it is successful or there is an error
- successCallback and failCallback functions allow for you to be explicit about what the UI behavior is in either situation
- In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for more example.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900