Pompair
Pompair

Reputation: 7319

ASP.NET MVC: Downloading an excel file

I'm downloading an excel file within C# action method the reutrns a FileResult, like this:

return File(bindata, "application/octet-stream", "mytestfile.xls");

When I manually navigate to the URL that corresponds with the above method, then I get the rendered out representation of the file. The file will not download with a Save As -dialog.

Is there a way to force the download to happen through Save As -dialog?

-pom-

Upvotes: 6

Views: 18626

Answers (3)

nikmd23
nikmd23

Reputation: 9113

I have a feeling you are getting this behavior because of the media type you are returning.

Try changing the media type to application/vnd.ms-excel like this:

return File(bindata, "application/vnd.ms-excel", "mytestfile.xls");

Upvotes: 5

alexl
alexl

Reputation: 6851

Can you try this:

return new FileContentResult(bindata, "application/vnd.ms-excel")
            {
                FileDownloadName = "mytestfile.xls")
            };

Hope this helps.

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

Normally when you specify a filename to the File method it automatically appends a Content-Disposition header so that the Save-As dialog always shows. So I am a bit surprised when you say that your code doesn't work. You could also try to manually set this header:

Response.AppendHeader("Content-Disposition", "attachment; filename=mytestfile.xls");

Upvotes: 8

Related Questions