1.上传
void submitinfo(Object sender,EventArgs e)
{
int size=307200;
int LimitWidth=120;
int LimitHeight=160;
try
{
if (FileUpload1.PostedFile.FileName == "")
{
//this.Upload_info.Text = "请选择上传文件!";
Response.Write("请选择上传文件!");
}
else
{
string filepath = FileUpload1.PostedFile.FileName; //得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg
// Response.Write(filepath);
//return;
string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg
int i = filename.LastIndexOf(".");
string extendname=filename.Substring(i, filename.Length - i);
if (!(extendname == ".jpg"))
{
Response.Write("图片格式错误,必须为.jpg格式的图片!");
return;
}//检查图片文件的格式
if (FileUpload1.PostedFile.ContentLength == 0 || FileUpload1.PostedFile.ContentLength >= size)
{
Response.Write("指定的文件大小不符合要求,大小必须小于300k!");
return;
}//检查图片文件的大小
Stream oStream = FileUpload1.PostedFile.InputStream;
System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);
int owidth = oImage.Width; //原图宽度
int oheight = oImage.Height; //原图高度
if (owidth > LimitWidth || oheight > LimitHeight)
{
Response.Write("超过允许的图片尺寸范围,照片尺寸必须为120*160!");
return ;
}//检查是否超出规定尺寸
string serverpath = Server.MapPath("~/app_uploads/ ") + filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg
FileUpload1.PostedFile.SaveAs(serverpath);//将上传的文件另存为
//this.Upload_info.Text = "上传成功!";
Response.Write("上传成功!");
insertPic(serverpath);//插入数据库
}
}
catch (Exception ex)
{
Response.Write("上传发生错误!原因是:" + ex.ToString());
// this.Upload_info.Text = "上传发生错误!原因是:" + ex.ToString();
}
}
2.存入数据库
void insertPic(String path){
FileStream fs=File.OpenRead(path);
byte[] content=new byte[fs.Length];
fs.Read(content,0,content.Length);
fs.Close();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["JaneConnection"].ConnectionString);
String sql = "insert into i_pic(pic) values(@pic)";
SqlCommand comm=new SqlCommand(sql,con);
con.Open();
try {
SqlParameter para3=new SqlParameter("@pic",SqlDbType.Image);
para3.Value=content;
comm.Parameters.Add(para3);
int add=comm.ExecuteNonQuery();
if(add>0)
{
Response.Write("成功插入图片!");
}
} catch (Exception e){
Response.Write(e.ToString());
}
}
3.从数据库中读取出来,用在页面上直接显示
void readPic(int _id){
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["JaneConnection"].ConnectionString);
String sql = "select pic from i_pic where id=@id";
SqlCommand comm=new SqlCommand(sql,con);
con.Open();
SqlParameter para4=new SqlParameter("@id",SqlDbType.Int);
para4.Value=_id;
comm.Parameters.Add(para4);
SqlDataReader reader=comm.ExecuteReader();
while(reader.Read())
{
Response.BinaryWrite((byte[])reader["pic"]);
//x_image=(byte[])reader["pic"];
}
reader.Close();
con.Close();
}
catch(Exception e)
{
Response.Write(e.ToString());
}
}
4.用Image控件显示:因为Image控件不能像byte[]直接显示图片,所以要倒一下,借用byte[]把它做成只显示图片的.aspx页,然后,在主页上放Image控件,控件的URL直接指向.aspx页就行了
<asp:Image ID=x_image Runat=server ImageUrl="~/inner/pic.aspx/"/>