Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

c# - byte[] to File Type in MVC 3

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).

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.)

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.

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?

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.

Any suggestions?

Example: If I have the following code

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You would return a FileContentResult.

In you controller, something like this:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...