插入图片的必要条件
在我们开始上传之前,有两件重要的事我们需要做:
#Form 标记的 enctype 属性应该设置成 enctype="multipart/form-data"
# 需要一个<input type=file>表单来使用户选择他们要上传的文件,同时我们需要导入 System.IO名称空间来处理流对象
把以上三点应用到aspx页面。同时我们需要对SqlServer做以下的准备。
# 需要至少含有一个图片类型的字段的表
# 如果我们还有另外一个变字符类型的字段来存储图片类型,那样会更好一些。
现在,我们准备了一个Sql表(包含了一个image数据类型的字段),还有<input type=file>标记。当然我们还得准备Submit按钮,以便用户在选择了图片以后提交。在这个按钮的Onclick事件里,我们需要读取选取图片的内容,然后把它存入到表里。那我们先来看看这个Onclick事件。
提交按钮的Onclick事件的代码:
Dim intImageSize As Int64
Dim strImageType As String
Dim ImageStream As Stream
Dim strImageType As String
Dim ImageStream As Stream
' Gets the Size of the Image
intImageSize = PersonImage.PostedFile.ContentLength
intImageSize = PersonImage.PostedFile.ContentLength
' Gets the Image Type
strImageType = PersonImage.PostedFile.ContentType
strImageType = PersonImage.PostedFile.ContentType
' Reads the Image
ImageStream = PersonImage.PostedFile.InputStream
ImageStream = PersonImage.PostedFile.InputStream
Dim ImageContent(intImageSize) As Byte
Dim intStatus As Integer
intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
Dim intStatus As Integer
intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
' Create Instance of Connection and Command Object
Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim myCommand As New SqlCommand("sp_person_isp", myConnection)
Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
Dim myCommand As New SqlCommand("sp_person_isp", myConnection)
' Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure
myCommand.CommandType = CommandType.StoredProcedure
' Add Parameters to SPROC
Dim prmPersonImage As New SqlParameter("@PersonImage", SqlDbType.Image)
prmPersonImage.Value = ImageContent
myCommand.Parameters.Add(prmPersonImage)
Dim prmPersonImage As New SqlParameter("@PersonImage", SqlDbType.Image)
prmPersonImage.Value = ImageContent
myCommand.Parameters.Add(prmPersonImage)
Dim prmPersonImageType As New SqlParameter("@PersonImageType", SqlDbType.VarChar, 255)
prmPersonImageType.Value = strImageType
myCommand.Parameters.Add(prmPersonImageType)
prmPersonImageType.Value = strImageType
myCommand.Parameters.Add(prmPersonImageType)
Try
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
Response.Write("New person successfully added!")
Catch SQLexc As SqlException
Response.Write("Insert Failed. Error Details are: " & SQLexc.ToString())
End Try
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
Response.Write("New person successfully added!")
Catch SQLexc As SqlException
Response.Write("Insert Failed. Error Details are: " & SQLexc.ToString())
End Try
这是怎么工作的呢?
PersonImage是HTMLInputFile控件的对象。首先需要获得图片的大小,可以使用下面的代码实现:
PersonImage是HTMLInputFile控件的对象。首先需要获得图片的大小,可以使用下面的代码实现:
intImageSize = PersonImage.PostedFile.ContentLength
然后返回图片的类型使用ContenType属性。最后,也是最重要的事就是取得Image Stream,这可以用以下代码实现:
ImageStream = PersonImage.PostedFile.InputStream
我们需要一个字节型数组来存储image 内容。读取整个图片可以使用Stream对象的Read方法来实现。Read(in byte[] buffer,int offset,int count)方法有三个参数。【关于Read方法的详细可以参看.Net FrameWorkSDK】他们是:
buffer
字节数组。此方法返回时,该缓冲区包含指定的字符数组,该数组的 offset 和 (offset + count) 之间的值由从当前源中读取的字节替换。
offset
buffer 中的从零开始的字节偏移量,从此处开始存储从当前流中读取的数据。
count
要从当前流中最多读取的字节数。
这个Read方法用以下代码实现:
intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
.
intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
.
现在,我们已经读取了整个图片的内容,下一步,我们要把这些内容存入到sql 表。我们将使用存储过程来完成插入图片类型和图片内容到sql 表。如果你浏览了上面的代码,你将会发现我们使用了sqldbtype.image的数据类型(datatype)。Ok了,完成了这些,我们也就成功的把图片存入到SqlServer中了。
SQL Server提供了一个特别的数据类型:image,它是一个包含binary数据的类型。下边这个例子就向你展示了如何将文本或照片放入到数据库中的办法。在这篇文章中我们要看到如何在SQL Server中存储和读取图片。
1、建立一个表:
在SQL SERVER中建立这样结构的一个表:
列名 类型 目的
ID Integer 主键ID
IMGTITLE Varchar(50) 图片的标题
IMGTYPE Varchar(50) 图片类型. ASP.NET要以辨认的类型
IMGDATA Image 用于存储二进制数据
ID Integer 主键ID
IMGTITLE Varchar(50) 图片的标题
IMGTYPE Varchar(50) 图片类型. ASP.NET要以辨认的类型
IMGDATA Image 用于存储二进制数据
2、存储图片到SQL SERVER数据库中
为了能存储到表中,你首先要上传它们到你的WEB 服务器上,你可以开发一个web form,它用来将客户端中TextBox web control中的图片入到你的WEB服务器上来。将你的 encType 属性设置为:myltipart/formdata.
Stream imgdatastream = File1.PostedFile.InputStream;
int imgdatalen = File1.PostedFile.ContentLength;
string imgtype = File1.PostedFile.ContentType;
string imgtitle = TextBox1.Text;
byte[] imgdata = new byte[imgdatalen];
int n = imgdatastream.Read(imgdata,0,imgdatalen);
string connstr=((NameValueCollection)Context.GetConfig("appSettings"))["connstr"];
int imgdatalen = File1.PostedFile.ContentLength;
string imgtype = File1.PostedFile.ContentType;
string imgtitle = TextBox1.Text;
byte[] imgdata = new byte[imgdatalen];
int n = imgdatastream.Read(imgdata,0,imgdatalen);
string connstr=((NameValueCollection)Context.GetConfig("appSettings"))["connstr"];
SqlConnection connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand
("INSERT INTO ImageStore(imgtitle,imgtype,imgdata)
VALUES ( @imgtitle, @imgtype,@imgdata )", connection );
("INSERT INTO ImageStore(imgtitle,imgtype,imgdata)
VALUES ( @imgtitle, @imgtype,@imgdata )", connection );
SqlParameter paramTitle = new SqlParameter
("@imgtitle", SqlDbType.VarChar,50 );
("@imgtitle", SqlDbType.VarChar,50 );
paramTitle.Value = imgtitle;
command.Parameters.Add( paramTitle);
command.Parameters.Add( paramTitle);
SqlParameter paramData = new SqlParameter( "@imgdata", SqlDbType.Image );
paramData.Value = imgdata;
command.Parameters.Add( paramData );
paramData.Value = imgdata;
command.Parameters.Add( paramData );
SqlParameter paramType = new SqlParameter( "@imgtype", SqlDbType.VarChar,50 );
paramType.Value = imgtype;
command.Parameters.Add( paramType );
paramType.Value = imgtype;
command.Parameters.Add( paramType );
connection.Open();
int numRowsAffected = command.ExecuteNonQuery();
connection.Close();
int numRowsAffected = command.ExecuteNonQuery();
connection.Close();
3、从数据库中恢复读取
现在让我们来从SQL Server中读取我们放入的数据吧!我们将要输出图片到你的浏览器上,你也可以将它存放到你要的位置。
private void Page_Load(object sender, System.EventArgs e)
{
string imgid =Request.QueryString["imgid"];
string connstr=((NameValueCollection)
Context.GetConfig("appSettings"))["connstr"];
string sql="SELECT imgdata, imgtype FROM ImageStore WHERE id = " + imgid;
SqlConnection connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if(dr.Read())
{
Response.ContentType = dr["imgtype"].ToString();
Response.BinaryWrite( (byte[]) dr["imgdata"] );
}
connection.Close();
}
{
string imgid =Request.QueryString["imgid"];
string connstr=((NameValueCollection)
Context.GetConfig("appSettings"))["connstr"];
string sql="SELECT imgdata, imgtype FROM ImageStore WHERE id = " + imgid;
SqlConnection connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if(dr.Read())
{
Response.ContentType = dr["imgtype"].ToString();
Response.BinaryWrite( (byte[]) dr["imgdata"] );
}
connection.Close();
}
要注意的是Response.BinaryWrite 而不是Response.Write.
上传文件到 Access 数据库
Image2Access.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace eMeng.Exam
{
///
/// Image2Access 的摘要说明。
///
public class Image2Access : System.Web.UI.Page
{
protected System.Web.UI.HtmlControls.HtmlInputText MyFileName;
protected System.Web.UI.HtmlControls.HtmlInputFile MyFile;
protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;
protected System.Web.UI.WebControls.DataGrid DG_Persons;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
BindGrid();
}
private void BindGrid()
{
string strCnn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("Image2Access.mdb");
OleDbConnection myConnection = new OleDbConnection(strCnn);
OleDbCommand myCommand = new OleDbCommand("SELECT * FROM Person", myConnection);
myCommand.CommandType = CommandType.Text;
try
{
myConnection.Open();
DG_Persons.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
DG_Persons.DataBind();
}
catch(OleDbException SQLexc)
{
Response.Write("提取数据时出现错误:" + SQLexc.ToString());
}
}
protected string FormatURL(object strArgument)
{
return "ReadImage.aspx?id=" + strArgument.ToString();
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
///
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///
private void InitializeComponent()
{
this.Submit1.ServerClick += new System.EventHandler(this.Submit1_ServerClick);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Submit1_ServerClick(object sender, System.EventArgs e)
{
//得到提交的文件
Stream fileDataStream = MyFile.PostedFile.InputStream;
//得到文件大小
int fileLength = MyFile.PostedFile.ContentLength;
//创建数组
byte[] fileData = new byte[fileLength];
//把文件流填充到数组
fileDataStream.Read(fileData,0,fileLength);
//得到文件名字
string fileTitle = MyFileName.Value;
//得到文件类型
string fileType = MyFile.PostedFile.ContentType;
//构建数据库连接,SQL语句,创建参数
string strCnn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("Image2Access.mdb");
OleDbConnection myConnection = new OleDbConnection(strCnn);
OleDbCommand command = new OleDbCommand ("INSERT INTO Person (PersonName,PersonEmail,PersonSex,PersonImageType,PersonImage)" + "VALUES (@PersonName,@PersonEmail,@PersonSex,@PersonImageType,@PersonImage)", myConnection);
System.Data.OleDb.OleDbParameter paramPersonName = new OleDbParameter("@PersonName", System.Data.OleDb.OleDbType.VarChar,50);
paramPersonName.Value = fileTitle; command.Parameters.Add(paramPersonName);
System.Data.OleDb.OleDbParameter paramPersonEmail = new OleDbParameter("@PersonEmail", System.Data.OleDb.OleDbType.VarChar,50);
paramPersonEmail.Value = "
mengxianhui@dotnet.aspx.cc";
command.Parameters.Add(paramPersonEmail);
System.Data.OleDb.OleDbParameter paramPersonSex = new OleDbParameter("@paramPersonSex", System.Data.OleDb.OleDbType.VarChar,50);
paramPersonSex.Value = "男"; command.Parameters.Add(paramPersonSex); System.Data.OleDb.OleDbParameter paramPersonImageType = new OleDbParameter("@PersonImageType", System.Data.OleDb.OleDbType.VarChar,50);
paramPersonImageType.Value = fileType;
command.Parameters.Add(paramPersonImageType);
System.Data.OleDb.OleDbParameter paramPersonImage = new OleDbParameter("@PersonImage", System.Data.OleDb.OleDbType.Binary);
paramPersonImage.Value = fileData;
command.Parameters.Add(paramPersonImage);
//打开连接,执行查询
myConnection.Open();
command.ExecuteNonQuery();
myConnection.Close();
}
}
}