Store uploaded file content in image field of SQL Server database and retrieve content back into its original file format
There is one requirement of storing file content in a database using Image data type. Image field can store up to 231-1 bytes and that equals around 2 GB. So you can store up to 2 GB data in image field of Microsoft SQL Server. Let us come to the point now; I was required to store uploaded file content in image field of database. File is uploaded through file upload control of HTML of course! While uploading the content you need to convert that content into byte array and then you can store it into the database. Now, how to convert file content into byte that I have displayed below with code.
Code: C#
Int32 intDocLength = File1.PostedFile.ContentLength;
byte[] bytDocTemp = new byte[intDocLength];
Stream objStream;
objStream = File1.PostedFile.InputStream;
objStream.Read(bytDocTemp, 0, intDocLength);
Now you can use bytDocTemp variable to store content of the file in the form of byte array into the database. Here, File1 is a file upload control and I used content length of the file to create an array of byte with exact size of the file.
I will show you how to retrieve file content from Image data type and showing it in its original form. You can display uploaded content of the file back to its original form with the following code:
Code: C#
Response.Clear();
Response.AddHeader(“Content-Disposition”, “attachment; filename=<filename>” + <File Extention>);
Response.ContentType = “application/octet-stream”;
Response.BinaryWrite(<byte array of the file>);
Response.End();
Here, replace <filename> with any of the file name that you need to display. File name must be without extension, and replace <File Extension> with your original file extension (like .doc, .pdf, .html etc). <byte array of the file> can be replaced with the content that you have fetched from the Image field of the database.
Whether you found this article useful or not? please provide your valuable comments.
Comments
Post a Comment