Setting up application to download a file in asp.net MVC - Nothing happening on return from download

I realize that variations on this question have been asked before. The best answer I have found is at

File download in Asp.Net MVC 2

But trying to follow those instructions did not solve the problem for me.

Long story short, the file is being retrieved correctly, the name, path and mime type are all correct, and no errors are thrown. No errors are thrown by the javascript on the client-side either.

The C# code that gets the file looks like this:

[HttpPost]
public FileResult DownloadFile(int fileId)
{
    ... get the file and file info
    return File(fileBytes, fileMimeType, fileName);
}

The javascript looks like this:

... set up for post here
$.post(settings.actions.downloadFile, {fileId: fileIdVar});

As I was saying, the post returns and nothing happens.

I have tried changing the post to a get, and the result was the same.

I have tried setting up a callback function that sets document.location.href to some random url on return from the download, but that just takes my browser to the page I specified. I cannot understand, from the explanation given in the link I provided, that is

"...Use document.location.href = ... to tell the browser to go to the url for downloading the file. It'll see the content disposition header and will display it as a download not as a page..."

What I'm supposed to point my browser to. document.location.href doesn't accept data, so I can't use it on its own, and using post without document.location.href returns nothing.

What could I be doing wrong?

Big thanks to responders for their time!

Answers


Just like the answer in the post you linked says, you can't download a file via AJAX.

In order to set the location, change your action to respond to GET requests and either add your file id to the query string or setup a route to handle it. Also, and you may already be doing this, but you'll need to make sure you set the Content-Dispostion header value to attachment.

window.location.href = settings.action.downloadFile + "?fileId=" + fileIdVar

Since you are using jQuery, you could use $.param to build the parameters for you.

You could also look into a plugin to provide an "AJAX like" experience.


Need Your Help

Make full site HTTPS / SSL? What performance / SEO issues & best practices still apply in 2012?

html performance forms ssl https

Note: There are existing question that look like duplicates (linked below) but most of them are from a few years ago. I'd like to get a clear and definitive answer that proves things either way.

GEOMETRY and GEOGRAPHY difference SQL Server 2008

sql sql-server

What is difference between GEOMETRY and GEOGRAPHY in SQL Server 2008?