asp.net上传图片保存到数据库的代码

数据库:保存图片的数据格式 图象二进制数据储存字段
前台:
复制代码 代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadWork.aspx.cs" Inherits="meishuguan.UploadWork" %>


























 



 



 






后台:
复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
namespace meishuguan
{
public partial class UploadWork : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UploadButton_Click(object sender, EventArgs e)
{
HttpPostedFile UpFile = UploadImage.PostedFile;
int ImageLength = UpFile.ContentLength;
if (ImageLength == 0)
{
MessageLabel.Text = "请选择要上传的图片";
return;
}
if (ImageLength > Int32.Parse(Application["MaxImageLength"].ToString()))
{
MessageLabel.Text = "图片大小不能大于2M";
return;
}
Stream ImageStream = UpFile.InputStream;
Byte[] ImageByte = new Byte[ImageLength];
ImageStream.Read(ImageByte, 0, ImageLength);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
string sqlstring = "insert into [Work](MID,image,length) values(@MID,@image,@length)";
SqlCommand command = new SqlCommand(sqlstring, connection);
command.Parameters.Add("@MID", System.Data.SqlDbType.Int).Value = Session["MID"].ToString();
command.Parameters.Add("@image", System.Data.SqlDbType.Image, ImageLength).Value = ImageByte;
command.Parameters.Add("@length", System.Data.SqlDbType.Int).Value = ImageLength;
connection.Open();
command.ExecuteNonQuery();
connection.Close();
MessageLabel.Text = "图片上传成功";
}
}
}

你可能感兴趣的:(asp.net上传图片保存到数据库的代码)