Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 655
TheJediCowboy Avatar asked Feb 23 '23 20:02

TheJediCowboy


1 Answers

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.

like image 164
vcsjones Avatar answered Mar 01 '23 22:03

vcsjones