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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x