Example of accessing a picture to a database in asp.net

Source: Internet
Author: User
Tags file upload log
asp.net| Example | data | database//Development environment: Windows 2000, SQLServer2000,. NET Framework SDK Official edition
Development language: C #, ASP.net
Introduction: Image storage and Reading in database
Author: engine
/*
Description: In ASP, we use Request.TotalBytes, Request.BinaryRead () to upload pictures, this abominable BinaryRead () method is very stupid, single file upload is no big deal, single if multiple pictures on the dedicated can spend a lot of strength ...! And now ASP.net will solve the previous ASP file upload a variety of problems, so that you in the ASP.net easily developed a powerful upload program, below you see examples.
*/
Note: Due to the author's limited level, mistakes are unavoidable, if found wrong please advise
Email:e_engine@21cn.com

/*
First in SQL Server to create a picture stored in the library table, imagedata column for the image of binary data storage fields, Imagecontenttype column for the image file type record field, Imagedescription column is the saving image file Description field, imagesize column is a stored image file length field, structured as follows:
CREATE TABLE [dbo]. [Imagestore] (
[imageID] [INT] IDENTITY (1, 1) not NULL,
[ImageData] [Image] Null
[Imagecontenttype] [varchar] (m) COLLATE chinese_prc_ci_as NULL,
[Imagedescription] [varchar] (m) COLLATE chinese_prc_ci_as NULL,
[ImageSize] [INT] Null
) on [PRIMARY] textimage_on [PRIMARY]
*/

The contents of the Uploadimage.aspx program are as follows:
<%@ Page inherits= "uploadimage.uploadimage" src= "UpLoadImage.cs" language= "C #"%>
<HTML><title> Upload Pictures </title>
<body bgcolor= "#FFFFFF" >
<form enctype= "Multipart/form-data" runat= "Server" id= "Form1" >
<table runat= "Server" Width= "M" align= "left" id= "Table1" cellpadding= "0" cellspacing= "0" border= "0" >
<TR>
<TD> Upload pictures (choose the pictures you want to upload) </TD>
<TD>
<input type= "File" id= "Up_file" runat= "Server" style= "width:320" accept= "text/*" name= "Up_file" >
</TD>
</TR>
<TR>
<TD>
File description (Add upload picture description, such as: Author, source)
</TD>
<TD>
<asp:textbox runat= "Server" width= "239" id= "Txtdescription" maintainstate= "false"/>
</TD>
</TR>
<TR>
<TD>
<asp:label runat= "Server" id= "txtmessage" forecolor= "Red" maintainstate= "false"/>
</TD>
<TD>
<asp:button runat= "Server" width= "239" text= "Upload Image"/>
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
//-------------------------------------------------------------------
The contents of the UpLoadImage.cs program are as follows:
Using System;
Using System.Web;
Using System.IO;
Using System.Data;
Using System.Data.SqlClient;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.HtmlControls;
Namespace Uploadimage
{
public class Uploadimage:page {
protected HtmlInputFile Up_file; HTMLControl, WebControls control objects
protected TextBox txtdescription;
protected Label txtmessage;
protected Int32 filelength = 0; Log file length variable
protected void Button_submit (System.Object sender, System.EventArgs e) {
Httppostedfile upfile = Up_file. PostedFile; Httppostedfile object, for reading image file properties
Filelength = Upfile.contentlength; Log file length
try {
if (Filelength = = 0) {//File length is zero
Txtmessage.text = "<b> Please select the file you want to upload </b>";
} else {
byte[] Filebytearray = new Byte[filelength]; Image file temporary storage byte array
Stream streamobject = Upfile.inputstream; Set up a data stream pair like
Read image file data, Filebytearray for data storage, 0 for data pointer position, filelnegth for data length
Streamobject.read (filebytearray,0,filelength);
Establish a SQL Server link
SqlConnection Con = new SqlConnection ("Data source=localhost;initial catalog=testdb; User Id=sa; pwd=; ");
String SQLCMD = "INSERT into Imagestore (ImageData, Imagecontenttype, Imagedescription, ImageSize) VALUES (@Image, @Conten Ttype, @ImageDescription, @ImageSize) ";
SqlCommand cmdobj = new SqlCommand (SQLCMD, Con);
CMDOBJ.PARAMETERS.ADD ("@Image", Sqldbtype.binary, Filelength). Value = Filebytearray;
CMDOBJ.PARAMETERS.ADD ("@ContentType", sqldbtype.varchar,50). Value = Upfile.contenttype; Record file type
Upload other single table data records
CMDOBJ.PARAMETERS.ADD ("@ImageDescription", sqldbtype.varchar,200). Value = Txtdescription.text;
Log file length, use when reading
CMDOBJ.PARAMETERS.ADD ("@ImageSize", sqldbtype.bigint,8). Value = Upfile.contentlength;
Con.open ();
Cmdobj.executenonquery ();
Con.close ();
Txtmessage.text = "<p><b>ok! you have successfully uploaded your picture </b>";/prompt Upload success
}
catch (Exception ex) {
Txtmessage.text = ex. Message.tostring ();
}}}}
//----------------------------------------------------------------------
Well, the picture has been uploaded to the database, what do you want to do now? Of course, read and display in the database in the Web page, please see the following program:
The contents of the Readimage.aspx program are as follows:
/-----------------------------------------------------------------------
<%@ Page inherits= "Readimage.maindisplay" src= "ReadImage.cs"%>
//----------------------------------------------------------------------
The contents of the ReadImage.cs program are as follows:
Using System;
Using System.Data;
Using System.Data.SqlClient;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.HtmlControls;
Namespace Readimage {
public class MainDisplay:System.Web.UI.Page {
public void Page_Load (System.Object sender, System.EventArgs e) {
int imgid = Convert.ToInt32 (request.querystring["Imgid"]); Imgid for picture ID
Establish a database link
SqlConnection Con = new SqlConnection ("Data source=king;initial catalog=testdb; User Id=sa; pwd=; ");
String SQLCMD = "SELECT * from Imagestore WHERE imageID = @ImageID";
SqlCommand cmdobj = new SqlCommand (SQLCMD, Con);
CMDOBJ.PARAMETERS.ADD ("@ImageID", SqlDbType.Int). Value = Imgid;
Con.open ();
SqlDataReader sqlreader = Cmdobj.executereader ();
Sqlreader.read ();
Response.ContentType = (string) sqlreader["Imagecontenttype"];//Set Output file type
Output image File binary system
Response.OutputStream.Write ((byte[]) sqlreader["ImageData"], 0, (int) sqlreader["imagesize"]);
Response.End ();
Con.close ();
It's easy, ^_^.
}
}
}
//--------------------------------------------------------------------
And finally, of course, we're going to show it on the Web page.
Showimage.hml
<body>
This is the image read from the database:
<body>
//------------------------------------------------------------------
Finally, the process of course, there are many improvements, I hope that we think more of the series can be written more image upload Program
Good Luck,engine

Related Article

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.