使用 ASP.NET 在 MySQL 中存储图像






3.10/5 (8投票s)
本文介绍如何设置 MySQL 数据库以使用 ASP.NET 存储图像并将其显示回浏览器。
引言
本文介绍如何使用 ASP.NET 将图像上传到 Web 服务器。所有数据都存储在 MySQL 数据库中。本文面向对 ASP.NET、C#、SQL 和关系数据库有一些了解的中级程序员。第一部分介绍如何设置数据库,第二部分介绍如何编写上传文件的代码以及如何将其作为图库查看。代码已经过 JPEG 和 GIF 文件的测试。
设置数据库
我使用的数据库是 MySQL。有关如何获取和安装 MySQL 的信息可以从此处获得。为了简化创建和与数据库交互的过程,我使用了 MySQL 控制中心。这允许以可视方式创建和与 MySQL 数据库交互。
MySQL 附带一个名为 test 的默认数据库。我将使用这个数据库。
接下来是创建一个名为file的表,其中包含以下列。
ID
– 选择将其作为时间戳,将其创建为表的主键。Extension
– 选择它为varchar
。Data
– 选择它为longblob
。
要连接到 MySQL 数据库,必须下载 MySQL ODBC 驱动程序。我在这篇文章中使用的是 MySQL ODBC 驱动程序 3.51 版本。所有与数据库交互的代码都放在 DataAccess
类中。
public class DataAccess
{
private string _strConn =
@"Driver= {MySQLODBC 3.51 Driver};SERVER=localhost;DATABASE=test;";
private OdbcConnection _objConn;
public DataAccess()
{
this._objConn = new OdbcConnection(this._strConn);
}
// This function adds the Images to database
public string addImage(byte [] buffer,string extension)
{
string strSql = "SELECT * FROM File";
DataSet ds = new DataSet("Image");
OdbcDataAdapter tempAP = new OdbcDataAdapter(strSql,this._objConn);
OdbcCommandBuilder objCommand = new OdbcCommandBuilder(tempAP);
tempAP.Fill(ds,"Table");
try
{
this._objConn.Open();
DataRow objNewRow = ds.Tables["Table"].NewRow();
objNewRow["Extension"] = extension;
objNewRow["Data"] = buffer;
ds.Tables["Table"].Rows.Add(objNewRow);
// trying to update the table to add the image
tempAP.Update(ds,"Table");
}
catch(Exception e){return e.Message;}
finally{this._objConn.Close();}
return null;
}
// This function to get the image data from the database
public byte [] getImage(int imageNumber)
{
string strSql = "SELECT * FROM File";
DataSet ds = new DataSet("Image");
OdbcDataAdapter tempAP = new OdbcDataAdapter(strSql,this._objConn);
OdbcCommandBuilder objCommand = new OdbcCommandBuilder(tempAP);
tempAP.Fill(ds,"Table");
try
{
this._objConn.Open();
byte [] buffer = (byte [])ds.Tables["Table"].Rows[imageNumber]["Data"];
return buffer;
}
catch{this._objConn.Close();return null;}
finally{this._objConn.Close();}
}
// Get the image count
public int getCount()
{
string strSql = "SELECT COUNT(Data) FROM File";
DataSet ds = new DataSet("Image");
OdbcDataAdapter tempAP = new OdbcDataAdapter(strSql,this._objConn);
OdbcCommandBuilder objCommand = new OdbcCommandBuilder(tempAP);
tempAP.Fill(ds,"Table");
try>
{
this._objConn.Open();
int count = (int)ds.Tables["Table"].Rows[0][0];
return count;
}
catch{this._objConn.Close();return 0;}
finally{this._objConn.Close();}
}
}
获取用户上传的文件
为了将文件上传到 Web 服务器,使用了一个非常简单的 ASP.NET Web 窗体,它由一个文件字段和一个提交按钮组成。项目中的 Web 窗体文件是Upload.aspx,代码放在Upload.aspx.cs中。该文件被获取并放入Page_Load
函数中的数据库中。现在,代码会查看Request.Files
集合。由于该接口只允许上传一个文件,因此,我们检查 IIS 上是否有一个文件正在等待处理。代码检查文件的 MIME 类型,如果它是图像,则接受它,否则只会显示一条消息,表明不支持该 MIME 类型。如果文件是图像,则数据以字节形式读取并使用DataAccess
类对象插入到 MySQL 数据库中。
private void Page_Load(object sender, System.EventArgs e)
{
//Checking if there are any files avaiable on IIS.
if(Request.Files.Count != 0)
{
HttpPostedFile httpFile = Request.Files[0];
// Checking for extension
string extension = this.getFileExtension(httpFile.ContentType);
if(extension == null )
{
Response.Write("Mime type not Supported");
return;
}
System.IO.BufferedStream bf = new BufferedStream(httpFile.InputStream);
byte[] buffer = new byte;
bf.Read(buffer,0,buffer.Length);
// Creating the database object
DataAccess data = new DataAccess();
// Adding files to the database.
data.addImage(buffer,extension);
Response.Write("Image Added!");
}
}
显示上传的文件
现在,为了向用户显示上传的文件,在名为View.aspx的文件中设置了另一个 Web 窗体。获取图像数据是通过另一个名为show.aspx的文件完成的。
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
Data.DataAccess data = new Data.DataAccess();
int imagenumber = 0;
try
{
imagenumber = int.Parse(Request.QueryString["image"]);
}
catch(System.ArgumentNullException ee)
{
imagenumber = 0;
}
byte [] buffer = data.getImage(imagenumber);
System.IO.MemoryStream stream1 = new System.IO.MemoryStream(buffer,true);
stream1.Write(buffer,0,buffer.Length);
Bitmap m_bitmap = (Bitmap) Bitmap.FromStream(stream1,true);
Response.ContentType = "Image/jpeg";
m_bitmap.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
}
View.aspx允许用户通过单击“下一个”链接转到下一个文件。