Miles
Miles

Reputation: 5726

Transfer Byte array from server to browser

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?

Upvotes: 2

Views: 10936

Answers (2)

Rubens Farias
Rubens Farias

Reputation: 57946

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.

Upvotes: 0

Quintin Robinson
Quintin Robinson

Reputation: 82335

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();

Upvotes: 7

Related Questions