您的位置:首页 > 编程语言 > ASP

ASP.NET 2.0中向数据库中上传图片

2008-03-25 10:59 627 查看
我在做的时候用到了,UpLoadFile控件来实现现的。但是有很多的不足的地方,希望大家有什么好的建议,请多多的发表。

首先在UpLoadImage.aspx页面加一个 UpLoadFile控件,一个用来显示图片的Button,和一个上传图片的Button2按钮。在Button后面的代码如下:

protected Int32 FileLength = 0; //这个是定义在事件外面的,表示图片的大小
protected void Button2_Click(object sender, EventArgs e)
{

HttpPostedFile Upfile = FileUpload1.PostedFile;// 表示的是要上传的图片
FileLength = Upfile.ContentLength;
try
{
if (FileLength == 0)
{
Response.Write("<script>alert('请选择要上传的文件!!!');</script>");
}
else
{
Stream StreamObject = Upfile.InputStream;
byte[] FileArray = new byte[FileLength];
StreamObject.Read(FileArray, 0, FileLength);
SqlConnection Con = new SqlConnection("Data Source=Localhost;Initial Catalog=test;User ID=sa;Pwd=;");
string sql = "insert into test values(@ImageData,@ImageSize)";
SqlCommand sqlcmd = new SqlCommand(sql, Con);
sqlcmd.Parameters.Add("@ImageData",SqlDbType.Binary,FileLength).Value=FileArray;
sqlcmd.Parameters.Add("@ImageSize",SqlDbType.BigInt,8).Value=Upfile.ContentLength;
Con.Open();
sqlcmd.ExecuteNonQuery();
Con.Close();
Response.Write("<script>alert('上传文件成功!!!');</script>");
}
}
catch(Exception ex)
{
Response.Write(ex.Message.ToString());
}
DropDownList1.Items.Clear();
bind();

}

然后就是在ShowImage.aspx中显示图片了,在显示图片的Button全面的代码是一个传值的过程:

protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("ShowImage.aspx?ID="+DropDownList1.SelectedItem);
}

接下来就是在ShowImage.aspx的Page_Load事件中的代码:

protected void Page_Load(object sender, EventArgs e)
{
int id = Convert.ToInt32(Request.QueryString["id"].ToString());
SqlConnection Con = new SqlConnection("Data Source=Localhost;Initial Catalog=test;User ID=sa;Pwd=;");
string sql = "SELECT * FROM test WHERE ImageId = @ImageID";
SqlCommand sqlcmd = new SqlCommand(sql, Con);
sqlcmd.Parameters.Add("@ImageID", SqlDbType.Int).Value =id;
Con.Open();
SqlDataReader sqldr = sqlcmd.ExecuteReader();
sqldr.Read();
//Response.ContentType = (string)sqldr[""];
Response.OutputStream.Write((byte[])sqldr["ImageData"], 0, (int)sqldr["ImageSize"]);
Response.End();
Con.Close();
}

整个的程序就基本完成了,这样就会把图片以二进制的形式,存储到数据库中了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: