create a simple aspx which has File upload control and a button. When user selects a file to upload, I am checking it for valid image type and converting it to array of Bytes. Then I will store that byte array into database. Below is the code,
if (objFileUpload.PostedFile !=null) { if (objFileUpload.PostedFile.ContentLength > 0) { // Get Posted File. HttpPostedFile objHttpPostedFile = objFileUpload.PostedFile;
// Check valid Image type. Create this function according to your need if (CheckValidFileType(objHttpPostedFile.FileName)) { // Find its length and convert it to byte array int intContentlength = objHttpPostedFile.ContentLength;
// Create Byte Array Byte[] bytImage =new Byte[intContentlength]; // Read Uploaded file in Byte Array objHttpPostedFile.InputStream.Read(bytImage,0, intContentlength); } }
}
Pass this Byte array to you DAL and use it for storing image in database.
Database db =DatabaseFactory.CreateDatabase();
string sqlCommand =“StoredProcedureName”;
DbCommand dbCommandWrapper = db.GetStoredProcCommand(sqlCommand);
db.AddInParameter(dbCommandWrapper,“@Image”,DbType.Binary,bytImage );
try { db.ExecuteNonQuery(dbCommandWrapper); } catch {throw; }
This is how you can store the Image in database. Retrieving the image is the same process. Write a SP which will return your image. Store this value in a Byte Array. Once you get the image in Byte array, write it on form as shown below,
Byte[] bytImage =Byte array retrieved from database. if (bytImage !=null) { Response.ContentType =“image/jpeg”; Response.Expires = 0; Response.Buffer =true; Response.Clear(); Response.BinaryWrite(bytImage); Response.End(); }
To use this at multiple places in your application, you create a page to which you can pass ID of Image and it will retrieve image from database and create image. Now on every page you require to show this image take <asp:Image> on that page and set its ImageURL property to the path of newly created user control. See the code below,
<asp:Image ID=”ViewImage” runat=”server” />
string strURL =“~/ViewImage.aspx?ID= 1 “ ; ViewImage.ImageUrl = strURL;
|
| Author: Prashant Mishra 26 Dec 2008 | Member Level: Bronze Points : 1 |
Brother Can you mention the namespaces and using directives name? also about objFileUpload???
|