如何在asp.net页面中显示sql server 数据库图片字段的图片?

jackiedlh 2003-10-10 11:25:24
以前sql server 数据库只是存储图片文件的目录与文件名,用asp.net的image控件可以轻松显示。现在想把图片文件以image字段格式保持在数据库中,不知道怎么读出和写入图片文件到数据库中?
...全文
163 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
树猫 2003-10-10
  • 打赏
  • 举报
回复
说明:在ASP中,我们用Request.TotalBytes、Request.BinaryRead()来上传图片,这个可恶的BinaryRead()方法非常笨,单个文件上传倒没什么大事,单如果多个图片上专可就花大气力了…!而现在ASP.Net中将会把解决以前ASP中文件上传的种种问题,使你在ASP.Net中轻轻松松开发出功能强大的上传程序,下面大家看看例子啦。



首先在SQL Server中建立一个图片存储的数库表,SqlScript如下:



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] (50) NULL ,
[img_data] [image] NULL ,
[img_contenttype] [varchar] (50) 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
------------------------------------------------------------
一、上传图片:
imgupload.aspx文件:
<%@ 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">
文件名 <input type="text" id="imgName" runat="server" NAME="imgName">
<br>
选择文件 <input id="UploadFile" type="file" runat="server" NAME="UploadFile">
<br>
<asp:button Text="上传" runat="server" ID="Button1" />
</form>
<a href="imgview.aspx?id=1" target="_blank">看图</a>
</body>
</HTML>



codebehind文件:
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>
/// 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)
{
// 在此处放置用户代码以初始化页面
}



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("file:/// );
}
}
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:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);



}
#endregion




}
}



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



二、浏览图片:
imgvies.aspx文件:
<%@ 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文件:
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>
/// 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:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);



}
#endregion
}
}




这样这个程序就完成了,简单吧。当然还很多改进之处,希望大家多想想多编编一定可以写出更多的图象上传程序。
comy 2003-10-10
  • 打赏
  • 举报
回复
http://www.csdn.net/develop/read_article.asp?id=17711

http://authors.aspalliance.com/das/insertimage.aspx

http://authors.aspalliance.com/das/readimage.aspx

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧