此问题经常被人问本文列出将文字和图片上传到数据库的方法包括Access数据库和SQL Server数据库
Access数据库代码
<%@ Page Language=C# EnableViewState=true %>
<%@ Import Namespace=SystemDataOleDb %>
<!DOCTYPE html PUBLIC //WC//DTD XHTML Transitional//EN transitionaldtd>
<script runat=server>
protected void Button_Click( object sender EventArgs e )
{
SystemIOStream fileDataStream = FileUploadPostedFileInputStream;
if (fileDataStreamLength < )
{
MsgText = 请选择文件;
return;
}
//得到文件大小
int fileLength = FileUploadPostedFileContentLength;
//创建数组
byte[] fileData = new byte[fileLength];
//把文件流填充到数组
fileDataStreamRead(fileData fileLength);
//得到文件类型
string fileType = FileUploadPostedFileContentType;
//构建数据库连接SQL语句创建参数
string strCnn = Provider=MicrosoftJetOLEDB;Data Source= + ServerMapPath(ImageAccessmdb);
OleDbConnection myConnection = new OleDbConnection(strCnn);
OleDbCommand command = new OleDbCommand(INSERT INTO Person (PersonNamePersonEmailPersonSexPersonImageTypePersonImage) +
VALUES (@PersonName@PersonEmail@PersonSex@PersonImageType@PersonImage) myConnection);
commandParametersAddWithValue(@PersonNameTextBoxText);
commandParametersAddWithValue(@PersonEmail mengxia);
commandParametersAddWithValue(@paramPersonSex 男);
commandParametersAddWithValue(@PersonImageType fileType);
commandParametersAddWithValue(@PersonImage fileData);
//打开连接执行查询
myConnectionOpen();
commandExecuteNonQuery();
myConnectionClose();
ResponseRedirect(RequestRawUrl);
}
protected void Page_Load( object sender EventArgs e )
{
if (!PageIsPostBack)
{
BindGrid();
}
}
private void BindGrid( )
{
string strCnn = Provider=MicrosoftJetOLEDB;Data Source=
+ ServerMapPath(ImageAccessmdb);
OleDbConnection myConnection = new OleDbConnection(strCnn);
OleDbCommand myCommand = new OleDbCommand(SELECT * FROM Person myConnection);
try
{
myConnectionOpen();
GridViewDataSource = myCommandExecuteReader(SystemDataCommandBehaviorCloseConnection);
GridViewDataBind();
}
catch (OleDbException SQLexc)
{
ResponseWrite(提取数据时出现错误 + SQLexcToString());
}
}
protected string FormatURL( object strArgument )
{
return ReadImageaspx?id= + strArgumentToString();
}
</script>
<html xmlns=>
<head runat=server>
<title>上传文件到数据库</title>
</head>
<body>
<form id=MengXianhui runat=server>
<asp:GridView ID=GridView runat=server AutoGenerateColumns=false>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%#Eval(PersonName) %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<%#Eval(PersonEmail) %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<%#Eval(PersonSex) %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<img src=<%#FormatURL(Eval(PersonID)) %> /></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<br />
姓名<asp:TextBox ID=TextBox runat=server></asp:TextBox>
<br />
照片<asp:FileUpload ID=FileUpload runat=server />
<asp:Button ID=btnUpload runat=server Text=上传 OnClick=Button_Click></asp:Button>
<p>
<asp:Label ID=Msg runat=server ForeColor=Red></asp:Label></p>
</form>
</body>
</html>
SQL Server数据库代码
<%@ Page Language=C# EnableViewState=true %>
<%@ Import Namespace=SystemDataSqlClient %>
<!DOCTYPE html PUBLIC //WC//DTD XHTML Transitional//EN transitionaldtd>
<script runat=server>
string strCnn = Persist Security Info=False;User ID=sa;Password=;Initial Catalog=Book;Server=(local);;
protected void Button_Click( object sender EventArgs e )
{
SystemIOStream fileDataStream = FileUploadPostedFileInputStream;
if (fileDataStreamLength < )
{
MsgText = 请选择文件;
return;
}
//得到文件大小
int fileLength = FileUploadPostedFileContentLength;
//创建数组
byte[] fileData = new byte[fileLength];
//把文件流填充到数组
fileDataStreamRead(fileData fileLength);
//得到文件类型
string fileType = FileUploadPostedFileContentType;
//构建数据库连接SQL语句创建参数
SqlConnection myConnection = new SqlConnection(strCnn);
SqlCommand command = new SqlCommand(INSERT INTO UserPhoto (UserNameContentTypePhoto) +
VALUES (@UserName@ContentType@Photo) myConnection);
commandParametersAddWithValue(@UserName TextBoxText);
commandParametersAddWithValue(@ContentType fileType);
commandParametersAddWithValue(@Photo fileData);
//打开连接执行查询
myConnectionOpen();
commandExecuteNonQuery();
myConnectionClose();
ResponseRedirect(RequestRawUrl);
}
protected void Page_Load( object sender EventArgs e )
{
if (!PageIsPostBack)
{
BindGrid();
}
}
private void BindGrid( )
{
SqlConnection myConnection = new SqlConnection(strCnn);
SqlCommand myCommand = new SqlCommand(SELECT * FROM UserPhoto Order By id DESC myConnection);
try
{
myConnectionOpen();
GridViewDataSource = myCommandExecuteReader(SystemDataCommandBehaviorCloseConnection);
GridViewDataBind();
}
catch (Exception SQLexc)
{
ResponseWrite(提取数据时出现错误 + SQLexcToString());
}
}
protected string FormatURL( object strArgument )
{
return ReadImageaspx?id= + strArgumentToString();
}
</script>
<html xmlns=>
<head id=Head runat=server>
<title>上传文件到数据库</title>
</head>
<body>
<form id=MengXianhui runat=server>
<asp:GridView ID=GridView runat=server AutoGenerateColumns=false>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%#Eval(UserName) %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<img src=<%#FormatURL(Eval(id)) %> /></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<br />
姓名<asp:TextBox ID=TextBox runat=server></asp:TextBox>
<br />
照片<asp:FileUpload ID=FileUpload runat=server />
<asp:Button ID=btnUpload runat=server Text=上传 OnClick=Button_Click></asp:Button>
<p>
<asp:Label ID=Msg runat=server ForeColor=Red></asp:Label></p>
</form>
</body>
</html>
显示图片
<%@ Page Language=C# %>
<%@ Import Namespace=SystemDataOleDb %>
<%@ Import Namespace=SystemDataSqlClient %>
<script runat=server>
protected void Page_Load( object sender EventArgs e )
{
////构建数据库连接SQL语句创建参数
//ACCESS数据库使用本注释部分
//string strCnn = Provider=MicrosoftJetOLEDB;Data Source= + ServerMapPath(ImageAccessmdb);
//OleDbConnection myConnection = new OleDbConnection(strCnn);
//OleDbCommand command = new OleDbCommand(select * from Person Where PersonID = + RequestQueryString[id] myConnection);
//myConnectionOpen();
//OleDbDataReader dr = commandExecuteReader();
//if (drRead())
//{
// ResponseClear();
// ResponseAddHeader(ContentType dr[PersonImageType]ToString());
// ResponseBinaryWrite((byte[])dr[PersonImage]);
//}
//drClose();
//myConnectionDispose();
//构建数据库连接SQL语句创建参数
string strCnn = Persist Security Info=False;User ID=sa;Password=;Initial Catalog=Book;Server=(local);;
SqlConnection myConnection = new SqlConnection(strCnn);
SqlCommand command = new SqlCommand(select * from UserPhoto Where id = + RequestQueryString[id] myConnection);
myConnectionOpen();
SqlDataReader dr = commandExecuteReader();
if (drRead())
{
ResponseClear();
ResponseAddHeader(ContentType dr[ContentType]ToString());
ResponseBinaryWrite((byte[])dr[Photo]);
}
drClose();
myConnectionDispose();
}
</script>
创建SQL数据表语句
CREATE TABLE [UserPhoto] (
[id] [int] IDENTITY ( ) NOT NULL
[UserName] [nvarchar] () COLLATE Chinese_PRC_CI_AS NOT NULL
[ContentType] [varchar] () COLLATE Chinese_PRC_CI_AS NOT NULL
[Photo] [image] NOT NULL
CONSTRAINT [PK_UserPhoto] PRIMARY KEY CLUSTERED
(
[id]
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO