Very simply, there are two parts to this, storing in inside DB and retrieving for display. This program works for C# + MS SQL. Before everything I assume that you created a table inside the database with a field picture with datatype image.
Part I: Storing in Database
a.) setup an input file with the name UploadFile.
<input id="UploadFile" type="file" runat="server">
b.) setup a button with the name btnUpload
<asp:imagebutton id="btnUpload" onclick="btnUpload_Click" runat="server" height="29" width="150" imageurl="images/buttons/upload_long.jpg"></asp:imagebutton>
c.) setup code behide for the button to be
if (Page.IsValid) {
String userId = Session["authenticated_userid"].ToString();
Stream imgStream = UploadFile.PostedFile.InputStream;
int imgLen = UploadFile.PostedFile.ContentLength;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData, 0, imgLen);
DB.userTableAdapter aAdapter = new // you need to set this up in your own DB.xsd
DB.userTableAdapter();
int rowsAffected = aAdapter.UpdatePicture(imgBinaryData, int.Parse(userId));
if (rowsAffected > 0) {
Response.Redirect("home.aspx"); // go back to same page
}
}
Part II: Retrieving stored image from DB
1.) Create a file call getImage.aspx and inside Page Load
protected void Page_Load(object sender, EventArgs e) {
String userId = Session["authenticated_userId"].ToString(); // get your own identified
DB.userTableAdapter aAdapter = new DB.userTableAdapter();
byte [] temp = aAdapter.GetPicture(int.Parse(userId));
if (temp == null) // in case we find nothing in db {
Stream s = File.OpenRead(Server.MapPath("images\\portrait.jpg"));
temp = new byte[s.Length];
s.Read(temp, 0, (int)s.Length);
Response.BinaryWrite(temp);
s.Dispose();
s.Close();
}
Response.BinaryWrite(temp);
}
2.) Wherever you want to show you image, just call the image as per normal
i.e. <img src="http://www.blogger.com/getImage.aspx" />
Done! Enjoy.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment