字节[]以文件类型MVC 3 [英] byte[] to File Type in MVC 3

查看:124
本文介绍了字节[]以文件类型MVC 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC应用程序,我最近配置了一个页面,以允许上传任意文件类型(与不适用这个问题有一定的限制)。

In my MVC application, I recently have configured a page to allow an arbitrary file type to be uploaded(with certain restrictions that dont apply to this question).

我存储文件在数据库中的字节[]数据类型,其基于该文件的扩展名保存的文件类型(请不要试图给我一个更好的选择,用于存储这些文件,我很清楚地知道,存储在数据库文件中是不是一个好的做法,但我们有需要,我们使用SQL Server保存这些文件的约束。)

I am storing the file as data type byte[] in the database, with the stored file type based off of the file extension(Please dont try to give me a better option for storing these files, I am well aware that storing files in the database is not a good practice, but we have a constraint that requires that we persist these files using SQL Server.)

就像我说的,让这个更糟的是,我存储文件的byte []数组在数据库中的列是类型的文本。这只是这样做我不担心与VARBINARY类型的限制。

As I was saying, to make this even worse, I am storing the byte[] array of the file in a column in the database which is of type text. This is only done so I dont have to worry about restrictions with the varbinary type.

我想知道的是,当请求的文件,什么是MVC 以这些文件与指定的文件扩展名返回给用户的最佳方式

What I want to know is, when a file is requested, what is the best way in MVC to return these files to the user with a specified file extension?

我已经能够做到这一点之前,Excel文件和一个AJAX调用我的控制器上的GET的行动,但我想知道是否有更好的方法来做到这一点。

I have been able to do this before with excel files and an AJAX call to a "GET" action on my controller, but I want to know if there is a better way to do it.

有什么建议?

例如:如果我有以下的code

Example: If I have the following code

string fileExtension = /*Some File Extension*/
byte[] data = MyDataContext.DocumentTable.First(p => p.DocumentUID == id);

我怎样才能然后用这个数据返回给用户指定文件格式的 fileExtension 最初坚持着。

How can I then return this data to the user in the specified file format using the fileExtension that was originally persisted.

修改我猜测的 FileResult 将是完成这一最简单的方法之一。

EDIT I am guessing that FileResult will be one of the easiest ways to accomplish this.

推荐答案

您将返回<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.filecontentresult.aspx\"><$c$c>FileContentResult.

在你的控制器,这样的事情:

In you controller, something like this:

 byte[] data = MyDataContext.DocumentTable.First(p => p.DocumentUID == id);
 return File(data, "text/plain", "myfile.txt");

在除了文件的扩展名,你需要为它指定一个名字为好。第二个参数是MIME类型。这是很重要的一些浏览器(如Firefox)来确定来打开文件的应用程序。 Firefox将preFER MIME类型在扩展。

In addition to the extension of the file, you need to specify a name for it as well. The 2nd parameter is the MIME type. This is important for some browsers (like FireFox) to determine which application to open your file with. Firefox will prefer the MIME type over the extension.

这篇关于字节[]以文件类型MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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