您的位置:首页 > 数据库

图片以二进制形式存到数据库中,并从数据库中读出显示在页面上

2007-07-02 21:56 543 查看
最近的一个.net项目,我要实现图片以二进制形式存到数据库中,并从数据库中读出显示在页面上。以前没做过类似的东东。经过查阅大量的资料,将实现思想先下来供大家参考。

1首先是上传文件。用html中的控件既可实现上传照片的操作。

2将控件得到的客户端地址转化为可以读出二进制数据的地址。此步是关键,需要用到System.IO.getpath将路径上传照片得到的路径转化一下。然后利用filestream控件将转后的地址把照片读到服务器上。注意服务器需要设置一下写的权限。

3。利用filestream读出写入指定路径的照片,以二进制形式存到数据库中。

4。从数据库读数据时,需要先把二进制数据用response.binarywrite的方法读到一个指定的页b上。

5。把要显示图片的页面a上的image控件的imageurl地址指定为页面b的网络相对地址。注意i给mageurl赋值时最好在后台赋,不要写死在前台。


<HTML>


<HEAD>


<title>多文件上传</title>




<script language="JavaScript">...


function addFile()




...{


var str = '<INPUT type="file" size="50" NAME="File">'


document.getElementById('MyFile').insertAdjacentHTML("beforeEnd",str)


}


</script>


</HEAD>


<body>


<form id="form1" method="post" runat="server" enctype="multipart/form-data">


<center>


<asp:Label Runat="server" ID="MyTitle"></asp:Label>


<P id="MyFile"><INPUT type="file" size="50" NAME="File"></P>


<P>


<input type="button" value="增加(Add)" onclick="addFile()">


<asp:Button Runat="server" Text="上传" ID="Upload"></asp:Button>


<input onclick="this.form.reset()" type="button" value="重置(ReSet)">


</P>


</center>


<P align="center">


<asp:Label id="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt" Width="513px"


BorderStyle="None" BorderColor="White"></asp:Label>


</P>


</form>


</body>


</HTML>


namespace updownsFiles




...{




/**//// <summary>


/// WebForm1 的摘要说明。


/// </summary>


public class WebForm1 : System.Web.UI.Page




...{


protected System.Web.UI.WebControls.Label MyTitle;


protected System.Web.UI.WebControls.Button Upload;


protected System.Web.UI.WebControls.Label strStatus;




private void Page_Load(object sender, System.EventArgs e)




...{


// 在此处放置用户代码以初始化页面


MyTitle.Text = "<h3>多文件上传</h3>";


Upload.Text = "开始上传";


if(this.IsPostBack)


this.SaveFiles();


}


private Boolean SaveFiles()




...{


//得到File表单元素


HttpFileCollection files = HttpContext.Current.Request.Files;


System.Text.StringBuilder strMsg=new System.Text.StringBuilder("上传的文件分别是:<hr color=red>");


try




...{


for(int intCount= 0; intCount< files.Count; intCount++)




...{




HttpPostedFile postedFile = files[intCount];


string fileName, fileExtension;


//获得文件名字


fileName = System.IO.Path.GetFileName(postedFile.FileName);


if (fileName != "")




...{


//获得文件名扩展


fileExtension = System.IO.Path.GetExtension(fileName);


strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br/>");


strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br/>");


strMsg.Append("上传文件的文件名:" + fileName + "<br/>");


strMsg.Append("上传文件的扩展名:" + fileExtension + "<br/><hr color=red>");




//可根据不同的扩展名字,保存文件到不同的文件夹


//注意:可能要修改你的文件夹的匿名写入权限。


postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("upFiles/") + fileName);


}


}


strStatus.Text = strMsg.ToString();


return true;


}


catch(System.Exception Ex)




...{


strStatus.Text = Ex.Message;




return false;


}


}






Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码


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


}


}



//上传
if(myFile.ContentLength != 0)
{
  try
  {
    System.Web.HttpPostedFile myFile = this.Request.Files[0];
//        string tmpFileName = myFile.FileName;
//        string myFileName = tmpFileName.Substring(tmpFileName.LastIndexOf("."));
//        string myFileMimeType = myFile.ContentType();
//        myFile.SaveAs(this.Server.MapPath("../" + myFileName));

    //读取到数组里面
    System.IO.Stream mystream = myFile.InputStream;
    byte[] Buffer = new byte[myFile.ContentLength];
    mystream.Read(Buffer,0,myFile.ContentLength);

    //打开数据库
    OracleConnection cn = new OracleConnection(ConfigurationSettings.AppSettings["sysDSN"]);
    cn.Open();

    //用参数方式写入数据库
    OracleCommand myComm = cn.CreateCommand();
    string sql = "insert into tmp(tmp_id,tmp_blob) values(tmp_seq.nextval,:tmp_blob)";
    myComm.CommandText = sql;
    myComm.Parameters.Add(":tmp_blob",OracleType.Blob,Buffer.Length).Value = Buffer;
    myComm.ExecuteNonQuery();
  }
  catch
  {
    //此处可加错误显示
  }
  finally
  {        
    cn.Close();
  }
}

在页面中,放一个Image控件,在后台指定它的链接地址如下:
----------------------------------------------------------------------
//为方便,写一个固定ID号tmp_id=103
this.Image1.ImageUrl = "showimg.aspx?tmp_id=103" ;

下面是显示图片的页面showimg.aspx后台代码,该页面不需要放任何东西.
--------------------------------------------------------------------
//创建数据库连接
OracleConnection myConnection = new OracleConnection(ConfigurationSettings.AppSettings["sysDSN"]);
myConnection.Open();

//打开数据库
OracleCommand myCommand = myConnection.CreateCommand();
string sql = "select tmp_blob from tmp where tmp_id = 103";
myCommand.CommandText = sql;
OracleDataReader myRead = myCommand.ExecuteReader();

//开始读取
myRead.Read();
//这个方法更直接
Byte[] Buffer = (Byte[])myRead[0];
//OracleLob myLob = myRead.GetOracleLob(0);
//长度是long,转为int32
//int myLength = Convert.ToInt32(myLob.Length);  
//Byte[] Buffer = new byte[myLength];      
//myLob.Read(Buffer,0,myLength);

//输出
this.Response.Clear();
//输出mime类型,根据上传的文件取到的mimetype,是什么我忘记了,自己写上,不过不写也没有关系.
this.Response.ContentType = "";
this.Response.BinaryWrite(Buffer);
this.Response.End();

比较全面的上传和下载文章
http://www.cnblogs.com/supercode/articles/173189.html

上传文件

下面给你一个上传图片及显示的例子(本例存入数据库,但也包含存在硬盘上,是注释掉的代码部分)

写入数据库

//上传
if(myFile.ContentLength != 0)
{
  try
  {
    System.Web.HttpPostedFile myFile = this.Request.Files[0];
//        string tmpFileName = myFile.FileName;
//        string myFileName = tmpFileName.Substring(tmpFileName.LastIndexOf("."));
//        string myFileMimeType = myFile.ContentType();
//        myFile.SaveAs(this.Server.MapPath("../" + myFileName));

    //读取到数组里面
    System.IO.Stream mystream = myFile.InputStream;
    byte[] Buffer = new byte[myFile.ContentLength];
    mystream.Read(Buffer,0,myFile.ContentLength);

    //打开数据库
    OracleConnection cn = new OracleConnection(ConfigurationSettings.AppSettings["sysDSN"]);
    cn.Open();

    //用参数方式写入数据库
    OracleCommand myComm = cn.CreateCommand();
    string sql = "insert into tmp(tmp_id,tmp_blob) values(tmp_seq.nextval,:tmp_blob)";
    myComm.CommandText = sql;
    myComm.Parameters.Add(":tmp_blob",OracleType.Blob,Buffer.Length).Value = Buffer;
    myComm.ExecuteNonQuery();
  }
  catch
  {
    //此处可加错误显示
  }
  finally
  {        
    cn.Close();
  }
}

在页面中,放一个Image控件,在后台指定它的链接地址如下:
----------------------------------------------------------------------
//为方便,写一个固定ID号tmp_id=103
this.Image1.ImageUrl = "showimg.aspx?tmp_id=103" ;

下面是显示图片的页面showimg.aspx后台代码,该页面不需要放任何东西.
--------------------------------------------------------------------
//创建数据库连接
OracleConnection myConnection = new OracleConnection(ConfigurationSettings.AppSettings["sysDSN"]);
myConnection.Open();

//打开数据库
OracleCommand myCommand = myConnection.CreateCommand();
string sql = "select tmp_blob from tmp where tmp_id = 103";
myCommand.CommandText = sql;
OracleDataReader myRead = myCommand.ExecuteReader();

//开始读取
myRead.Read();
//这个方法更直接
Byte[] Buffer = (Byte[])myRead[0];
//OracleLob myLob = myRead.GetOracleLob(0);
//长度是long,转为int32
//int myLength = Convert.ToInt32(myLob.Length);  
//Byte[] Buffer = new byte[myLength];      
//myLob.Read(Buffer,0,myLength);

//输出
this.Response.Clear();
//输出mime类型,根据上传的文件取到的mimetype,是什么我忘记了,自己写上,不过不写也没有关系.
this.Response.ContentType = "";
this.Response.BinaryWrite(Buffer);
this.Response.End();

/// <summary>
/// 文件上传
/// </summary>
/// <param name="path">路径</param>
/// <returns>返回 TRUE FALSE</returns>
private Boolean SaveFiles(string path)
{
///'遍历File表单元素
HttpFileCollection files = HttpContext.Current.Request.Files;
try
{
for(int iFile = 0; iFile < files.Count; iFile++)
{
HttpPostedFile postedFile = files[iFile];
string fileExtension;
string fileName = System.IO.Path.GetFileName(postedFile.FileName);
if (fileName != "")
{
fileExtension = System.IO.Path.GetExtension(fileName);
if(File.Exists(path+"//"+fileName))
{
postedFile.SaveAs(path+"//(新)"+ fileName);
}
else
{
postedFile.SaveAs(path+"//"+ fileName);
}
}
}
return true;
}
catch
{
return false;
}
}

System.Web.HttpPostedFile myFile = this.Request.Files[0];
string tmpFileName = myFile.FileName;
string myFileName = tmpFileName.Substring(tmpFileName.LastIndexOf("."));
string myFileMimeType = myFile.ContentType();
myFile.SaveAs(this.Server.MapPath("../" + myFileName));

内容: 上传到数据库中
SQL Server提供了一个特别的数据类型:image,它是一个包含binary数据的类型。下边这个例子就向你展示了如何将文本或照片上传到数据库中的办法。在这篇文章中我们要看到如何在SQL Server中存储和读取图片。

  1、建立一个表:

  在SQL SERVER中建立这样结构的一个表:

列名 类型 目的
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"];

SqlConnection connection = new SqlConnection(connstr);

SqlCommand command = new SqlCommand
         ("INSERT INTO ImageStore(imgtitle,imgtype,imgdata)
         VALUES ( @imgtitle, @imgtype,@imgdata )", connection );

SqlParameter paramTitle = new SqlParameter
         ("@imgtitle", SqlDbType.VarChar,50 );

paramTitle.Value = imgtitle;
command.Parameters.Add( paramTitle);

SqlParameter paramData = new SqlParameter( "@imgdata", SqlDbType.Image );
paramData.Value = imgdata;
command.Parameters.Add( paramData );

SqlParameter paramType = new SqlParameter( "@imgtype", SqlDbType.VarChar,50 );
paramType.Value = imgtype;
command.Parameters.Add( paramType );

connection.Open();
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();
}

  要注意的是Response.BinaryWrite 而不是Response.Write.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐