Image storage and Reading in database

Source: Internet
Author: User
Tags file upload generator modify tostring visual studio
Data | Database development environment: Windows 2000, SQLServer2000,. Net Framework SDK Official edition
Development language: C #, ASP.net
Description: Image storage and Reading in database



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.



First, create a database table of pictures stored in SQL Server, Sqlscript as follows:



if exists (SELECT * from dbo.sysobjects WHERE id = object_id (N) [dbo].[ Image] ") and OBJECTPROPERTY (ID, N" isusertable ") = 1)
drop table [dbo]. [Image]
Go



CREATE TABLE [dbo]. [Image] (
[IMG_PK] [INT] IDENTITY (1, 1) not NULL,
[Img_name] [varchar] (m) NULL,
[Img_data] [Image] Null
[Img_contenttype] [varchar] (m) NULL
) on [PRIMARY] textimage_on [PRIMARY]
Go



ALTER TABLE [dbo]. [Image] With NOCHECK ADD
CONSTRAINT [Pk_image] PRIMARY KEY nonclustered
(
[IMG_PK]
) on [PRIMARY]
Go
------------------------------------------------------------
First, upload pictures:
Imgupload.aspx file:
<%@ Page language= "C #" codebehind= "Imgupload.aspx.cs" autoeventwireup= "false" inherits= " Study.uploadimage.imgupload "%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<title>imgupload</title>
<meta name= "generator" content= "Microsoft Visual Studio 7.0" >
<meta name= "Code_language" content= "C #" >
<meta name= "vs_defaultClientScript" content= "JavaScript" >
<meta name= "vs_targetschema" content= "http://schemas.microsoft.com/intellisense/ie5" >
</HEAD>
<body>
<form enctype= "Multipart/form-data" runat= "Server" id= "Form1" Name= "Form1" >
FileName <input type= "text" id= "imgname" runat= "Server" name= "Imgname" >
<br>
Select File <input id= "UploadFile" type= "file" runat= "server" name= "UploadFile" >
<br>
<asp:button text= "Upload" runat= "server" id= "Button1"/>
</form>
<a href= "imgview.aspx?id=1" target= "_blank" > See map </a>
</body>
</HTML>



Codebehind file:
Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Web;
Using System.Web.SessionState;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.HtmlControls;
Using System.IO;
Using System.Data.SqlClient;



Namespace Study.uploadimage
{
<summary>
Summary description of the imgupload.
</summary>
public class Imgupload:System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.HtmlControls.HtmlInputText imgname;
protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile;

private void Page_Load (object sender, System.EventArgs e)
{
Place user code here to initialize page
}



private void Button1_Click (object sender, System.EventArgs e)
{
Stream Imgstream;
int Imglen;
String Imgname_value;
String Imgcontenttype;
String Imguploadedname;

Imgstream = UploadFile.PostedFile.InputStream;
Imglen = UploadFile.PostedFile.ContentLength;
Imguploadedname = UploadFile.PostedFile.FileName;
Byte[] Imgbinarydata=new Byte[imglen];
Imgcontenttype = UploadFile.PostedFile.ContentType;
Imgname_value = Imgname.value;



Try
{
if (Imgname_value. Length < 1)
{
Imgname_value = Getlastrightof ("\", imguploadedname);
}
}
catch (Exception myEx)
{
Response.Write (Myex.message);
}



int n = imgstream.read (imgbinarydata, 0, Imglen);
int numrowsaffected = Mydatabasemethod (Imgname_value, Imgbinarydata, Imgcontenttype);
if (numrowsaffected > 0)
Response.Write ("<BR> uploaded image");
Else
Response.Write ("<BR> An error occurred uploading the IMAGE.D");
}
public string Getlastrightof (String lookfor,string myString)
{
int strpos;
Strpos = Mystring.lastindexof (lookfor);
Return mystring.substring (Strpos + 1);
}
public int Mydatabasemethod (string imgname,byte[] imgbin,string imgcontenttype)
{
SqlConnection connection = new SqlConnection (application["Test_conn"). ToString ());
String sql= "INSERT into Image (img_name,img_data,img_contenttype) VALUES (@img_name, @img_data, @img_contenttype)";
SqlCommand command=new SqlCommand (sql,connection);

SqlParameter param0=new SqlParameter ("@img_name", sqldbtype.varchar,50);
Param0. Value = imgname;
Command. Parameters.Add (PARAM0);



SqlParameter param1=new SqlParameter ("@img_data", sqldbtype.image);
param1. Value = Imgbin;
Command. Parameters.Add (param1);

SqlParameter param2 =new SqlParameter ("@img_contenttype", sqldbtype.varchar,50);
Param2. Value = Imgcontenttype;
Command. Parameters.Add (PARAM2);

Connection. Open ();
int numrowsaffected = command. ExecuteNonQuery ();
Connection. Close ();
return numrowsaffected;
}



#region Web Form Designer generated code
Override protected void OnInit (EventArgs e)
{
//
CodeGen: This call is required for the ASP.net Web forms Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
</summary>
private void InitializeComponent ()
{
This. Button1.Click + = new System.EventHandler (this. Button1_Click);
This. Load + = new System.EventHandler (this. Page_Load);



}
#endregion




}
}



------------------------------------------------------------



Second, browse the picture:
Imgvies.aspx file:
<%@ Page language= "C #" codebehind= "Imgview.aspx.cs" autoeventwireup= "false" inherits= "Study.uploadimage.imgview" %>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<title>imgview</title>
<meta name= "generator" content= "Microsoft Visual Studio 7.0" >
<meta name= "Code_language" content= "C #" >
<meta name= "vs_defaultClientScript" content= "JavaScript" >
<meta name= "vs_targetschema" content= "http://schemas.microsoft.com/intellisense/ie5" >
</HEAD>
<body ms_positioning= "GridLayout" >
</body>
</HTML>



Codebehind file:
Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Web;
Using System.Web.SessionState;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.HtmlControls;
Using System.Data.SqlClient;



Namespace Study.uploadimage
{
<summary>
Summary description of the Imgview.
</summary>
public class Imgview:System.Web.UI.Page
{

private void Page_Load (object sender, System.EventArgs e)
{
SqlConnection mydsn = new SqlConnection (application["Test_conn"). ToString ());
Mydsn.open ();



int imgid = Int. Parse (request.querystring["id"]);
String sqltext = "Select Img_name, Img_data, img_contenttype from image where img_pk=" + imgid;
Trace.Write (SQLTEXT);
SqlCommand mycommand = new SqlCommand (SQLText, MYDSN);
SqlDataReader Dr =mycommand.executereader ();
if (Dr. Read ())
{
Response.ContentType = (dr["Img_contenttype"). ToString ());
Response.BinaryWrite ((byte[]) dr["Img_data");
}
Mydsn.close ();
}



#region Web Form Designer generated code
Override protected void OnInit (EventArgs e)
{
//
CodeGen: This call is required for the ASP.net Web forms Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
</summary>
private void InitializeComponent ()
{
This. Load + = new System.EventHandler (this. Page_Load);



}
#endregion
}
}




So this program is complete, simple. Of course there are a lot of improvements, I hope that we think more of the series can write more image upload program.

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.