ASP.NET MVC: Downloading an excel file

2019-04-07 22:44发布

问题:

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-

回答1:

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


回答2:

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


回答3:

Can you try this:

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

Hope this helps.