无论MVC中的文件类型如何,都可以从FileSystem下载文件 [英] Download File from FileSystem no matter the file type in MVC

查看:126
本文介绍了无论MVC中的文件类型如何,都可以从FileSystem下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从控制器方法中下载文件-该文件可以是任何文件类型。我在Stackoverflow中可以找到的所有内容都是从数据库下载的,或者文件类型已知。从到目前为止我发现的代码中,这就是我的代码:

I need to download a file from my controller method - that can be of any file type. Everything I can find in Stackoverflow is either downloading from the database or the file type is known. From the code I have found so far this is my code:

public FilePathResult ViewAttachment(string filePath, string fileName)
{
     byte[] fileData = System.IO.File.ReadAllBytes(filePath);
     string contentType = MimeMapping.GetMimeMapping(filePath);

     return File(fileData, contentType, filePath);
}

不幸的是,这在返回文件行上显示了一个错误:

Unfortunately this is giving me an error on the return file line saying:


无法将类型'System.Web.Mvc.FileConentResult'显式转换为
'System.Web.Mvc.FilePathResult'

Cannot explicitly convert type 'System.Web.Mvc.FileConentResult' to 'System.Web.Mvc.FilePathResult'


推荐答案

好,异常文本是不言自明的。

Well, exception text is self-explanatory.

File 方法返回 FileContentResult 的实例,而不是 FilePathResult (和 FileContentResult 并非从 FilePathResult 继承而来

File method returns instance of FileContentResult, not FilePathResult (and FileContentResult doesn't inherited from FilePathResult so explicit cast is impossible).

应该是

public FileContentResult ViewAttachment(string filePath, string fileName)

甚至 ActionResult 是继承自所有xxResult类型的最常见类型。

or even ActionResult as most common type all xxResult types inherited from.

public ActionResult ViewAttachment(string filePath, string fileName)

这篇关于无论MVC中的文件类型如何,都可以从FileSystem下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆