ASP.NET MVC: Downloading an excel file

旧城冷巷雨未停 提交于 2020-01-22 20:06:05

问题


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.



来源:https://stackoverflow.com/questions/7390749/asp-net-mvc-downloading-an-excel-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!