Byte [] to file type in MVC 3

In my MVC application, I recently set up a page that allows you to load an arbitrary file type (with some restrictions that do not apply to this issue).

I save the file as the byte [] data type in the database, with the saved file type based on the file extension (please do not try to give me the best option for storing these files, I well know that storing files in the database is not a good practice , but we have a limitation that requires us to save these files using SQL Server.)

As I said, to make this even worse, I save an array of byte [] files in a database column that is of type text . This is only done because I do not have to worry about limitations with the varbinary type.

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

I was able to do this before using excel files and calling AJAX for the "GET" action on my controller, but I want to know if there is a better way to do this.

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 return this data to the user in the specified file format using fileExtension , which was originally saved.

EDIT I assume FileResult will be one of the easiest ways to do this.

+4
source share
1 answer

You will return a FileContentResult .

Your controller has something like this:

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

In addition to the file extension, you also need to provide a name for it. The second parameter is the MIME type. It is important for some browsers (e.g. FireFox) to determine which application to open the file. Firefox prefers the MIME type over the extension.

+8
source

All Articles