在asp.net-mvc中打开一个文件

时间:2012-12-31 08:36:35

标签: sql-server asp.net-mvc

如何在asp.net mvc应用程序中打开.docx,.doc,.xls或.ppt文件,考虑到我的文件存储在数据库中。我可以通过编写以下行

在记事本中打开一个css文件
return File(("~/Content/Site.css"), ("text/css"));

2 个答案:

答案 0 :(得分:1)

File实用程序方法(对于FileResult)有一个重载,它接受一个流或一个字节数组(db中的文件可以作为流或字节数组提供。

  var bytes = db.GetFile(); //i'm assuming this method will return a byte array
   return File(bytes, 
     "application/vnd.openxmlformats-officedocument.wordprocessingml.document");

要使用特定文件名下载文件,您可以使用另一个重载。

return File(bytes, 
       "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "filename.docx");

答案 1 :(得分:0)

在我看来,您不需要“打开文件”,但您需要客户端能够从您的应用程序下载文件,而不是客户端对下载的文件执行任何操作。在大多数情况下,浏览器将显示一个保存/打开对话框,但这是最终用户客户端的工作(可能他安装了一些插件?),而不是该网站。

但是,要告诉网站提供办公室,有一个list of content types here,您感兴趣的是:

docx -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
pptx -> "application/vnd.openxmlformats-officedocument.presentationml.presentation"
xlsx -> "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

所以你需要做一些像(伪代码)

的事情
Dictionary<string, string> contentTypes = new Dictionary<string, string>();
contentTypes.Add("docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document");
contentTypes.Add("pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation");
contentTypes.Add("xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");;

string fileType = ...;

var result = new File(fileContents, contentTypes[fileType],"fileName."+fileType);
return result;