Save the image to the database table, read the image from the database table, and display it

Source: Internet
Author: User
Author: lxc Source: blog Park Release Date: Read: 293 Original article links [favorites]

I. page file. aspx

<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "PictureDeal. aspx. cs" Inherits = "MyProject. PictureDeal" %>

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Input id = "File1" runat = server type = "file"/> & nbsp; <asp: Button runat = server ID = btnUpFile
Text = UpFile onclick = "btnUpFile_Click"/>

& Nbsp; <asp: Button runat = server ID = btnDisplayPicture Text = "DisplayPic"
Onclick = "btnDisplayPicture_Click"/>

<Br/>


<Asp: Label runat = server ID = lblMsg EnableViewState = false> </asp: Label>

<Asp: Repeater runat = server ID = Rept>
<HeaderTemplate>
<Table cellpadding = 0 cellspacing = 0>

</HeaderTemplate>
<ItemTemplate>
<Tr>
<Td colspan = 3 align = left> <% # Eval ("ImageID") %> </td>
</Tr>

<Tr>
<Td style = "border: solid 1px gray;"> <% # Eval ("ImageType") %> </td>
<Td style = "border: solid 1px gray;"> <% # Eval ("ImageLength", "{0: N}") %> </td>
<Td style = "border: solid 1px gray;"> "height = 100 width = 200/> </td>
</Tr>

<Tr>
<Td colspan = 3> <% # (Container. ItemIndex + 1) % 2 = 0? "<Hr style = 'color: blue; '/>": String. Empty %> </td>
</Tr>

</ItemTemplate>

<% -- <SeparatorTemplate>
<Tr>
<Td colspan = 3 align = left> </Tr>
</SeparatorTemplate> -- %>

<FooterTemplate>
<Tr>
<Td colspan = 3> </Tr>
</Table>
</FooterTemplate>
</Asp: Repeater>
 
</Div>
</Form>
 
</Body>
</Html>

Ii. Page code file. cs

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. UI;
Using System. Web. UI. WebControls;

Using System. IO;
Using System. Data;
Using System. Data. SqlClient;

Namespace MyProject
{
Public partial class PictureDeal: System. Web. UI. Page
{

String strCon = System. Configuration. ConfigurationManager. receivettings ["ConnStr"]. ToString ();

Protected void Page_Load (object sender, EventArgs e)
{

}

// Upload and save the image to the database

Protected void btnUpFile_Click (object sender, EventArgs e)
{
String strJs = string. Empty;

If (File1.PostedFile. ContentLength> 0)
{
If (System. IO. Path. GetExtension (File1.PostedFile. FileName) = ". jpg ")
{
// String strPath = Server. MapPath (@"~ \ File ");
// StrPath = System. IO. Path. Combine (strPath, System. IO. Path. GetFileName (File1.PostedFile. FileName ));

// File1.PostedFile. SaveAs (strPath );

String strGuid = System. Guid. NewGuid (). ToString ();

Try
{

Using (SqlConnection sqlcon = new SqlConnection (strCon ))
{
Int intfileLength = File1.PostedFile. ContentLength;
String strfileType = File1.PostedFile. ContentType;

Stream fileStream = File1.PostedFile. InputStream;

Byte [] imgBytes = new byte [intfileLength];

FileStream. Read (imgBytes, 0, intfileLength );

SqlCommand sqlCmd = new SqlCommand ("insert into tbImageFile (ImageID, ImageType, ImageContent, ImageLength) values (@ ImageID, @ ImageType, @ ImageContent, @ ImageLength)", sqlcon );

SqlParameter p1 = new SqlParameter ("@ ImageID", strGuid );

SqlParameter p2 = new SqlParameter ("@ ImageType", strfileType );

SqlParameter p3 = new SqlParameter ("@ ImageContent", imgBytes );

SqlParameter p4 = new SqlParameter ("@ ImageLength", intfileLength );

SqlCmd. Parameters. Add (p1 );
SqlCmd. Parameters. Add (p2 );
SqlCmd. Parameters. Add (p3 );
SqlCmd. Parameters. Add (p4 );

Sqlcon. Open ();

If (sqlCmd. ExecuteNonQuery ()> 0)
{
ImgDisplay. Src = "HandlerPicture. ashx? ImageID = "+ strGuid;

LblMsg. Text = "<script language = javascript> alert ('added successfully'); </script> ";
}
Else
{
LblMsg. Text = "<script language = javascript> alert ('add failed'); </script> ";
}

FileStream. Dispose ();

}

}
Catch (Exception ex)
{
Throw ex;
}

}
Else
{
StrJs = "<script language = javascript> alert ('incorrect file format '); </script> ";
LblMsg. Text = strJs;
}
}
Else
{
StrJs = "<script language = javascript> alert ('upload A file'); </script> ";
LblMsg. Text = strJs;
}
}

// Display image information

Protected void btnDisplayPicture_Click (object sender, EventArgs e)
{
Using (SqlConnection sqlCon = new SqlConnection (strCon ))
{
SqlCommand sqlCmd = new SqlCommand ("select ImageID, ImageContent, ImageLength, ImageType from tbImageFile", sqlCon );

SqlCon. Open ();

SqlDataAdapter sqlDA = new SqlDataAdapter (sqlCmd );

DataSet myDs = new DataSet ();

SqlDA. Fill (myDs );

If (myDs. Tables [0]. Rows. Count> 0)
{
Rept. DataSource = myDs. Tables [0]. DefaultView;

Rept. DataBind ();

}

}
}

}
}

III.HandlerPicture. ashxRead the image from the database and write the binary string to the http output stream.

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;

Using System. IO;
Using System. Data;
Using System. Data. SqlClient;

Namespace MyProject
{
/// <Summary>
/// Obtain the image content from the database.
/// </Summary>

Public class HandlerPicture: IHttpHandler
{
String strCon = System. Configuration. ConfigurationManager. receivettings ["ConnStr"];
Public void ProcessRequest (HttpContext context)
{
Context. Response. ContentType = "image/jpg ";
String strGuid = context. Request. QueryString ["ImageID"]. ToString ();

Using (SqlConnection sqlCon = new SqlConnection (strCon ))
{
SqlCommand sqlCmd = new SqlCommand ("select ImageContent from tbImageFile where ImageID = @ ImageID", sqlCon );

SqlParameter p1 = new SqlParameter ("@ ImageID", strGuid );

SqlCmd. Parameters. Add (p1 );

SqlCon. Open ();

Byte [] bytes = (byte []) sqlCmd. ExecuteScalar ();
Context. Response. BinaryWrite (bytes );
}
}

Public bool IsReusable
{
Get
{
Return true;
}
}
}
}

Note: add the following lines to the <Add verb = "*" path = "HandlerPicture. ashx" type = "MyProject. HandlerPicture"/>

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.