views:

164

answers:

2

I have a database column that contains the contents of a file. I'm converting this into a byte[] on the server (I don't want to save the file to the disk) and then want to send this to the client to download. The file can be any thing (pdfs, pics, word, excel, etc).

I have the file name so I know the extension but I'm not sure how the best way to send it to the client is. Here's where I'm currently at:

string fileName = ds.Tables[0].Rows[0]["form_file_name"].ToString();
byte[] fileContents = (byte[])ds.Tables[0].Rows[0]["form_file_contents"];

Where do I go from here?

+1  A: 

You should be able to write it out to the client via something like this...

Response.Clear();
Response.AddHeader("Content-Length", fileContents.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=FILENAME");
Response.OutputStream.Write(fileContents, 0, fileContents.Length);
Response.Flush();
Response.End();
Quintin Robinson
Or Response.BinaryWrite(fileContents) instead of writing to the OutputStream.
Guffa
Good call on the BinaryWrite.
Quintin Robinson
A: 

I'd a similar situation here; if you're dealing with files, you should consider what happens if you have a big one in database.

You could use DataReader.GetBytes() as in Memory effective way to read BLOB data in C#/SQL 2005 and write that data in chunks. This is a better approach since you don't need have entire file in memory, but just a small piece everytime.

Using this idea, you could to write code to read 64k data chunks and write them like Quintin Robinson said.

Rubens Farias