龍騎少校

玩的就是技术。ko!!!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

asp.net图片上传

Posted on 2009-09-12 11:42  龍騎少校  阅读(527)  评论(0)    收藏  举报
using System; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Data.SqlClient; 
using System.IO; 
using System.Drawing; 
using System.Drawing.Imaging; 

namespace WebApplication4 

    
public partial class _Default : System.Web.UI.Page 
    

        
string filename = "";      //文件名 
        string yanzhenggeshi = ""//验证文件扩展名 
        string path = "";          //上传的文件路径 
        System.Drawing.Image image; //画图 
        string url = "server=.;uid=sa;password=12345;database=pubs";  
        
protected void Page_Load(object sender, EventArgs e) 
        

            
if (!IsPostBack) 
            

                bandlist(); 
            }
 
        }
 
        
//上传至项目文件夹photo 
        protected void Button1_Click(object sender, EventArgs e) 
        

            
string ss = yanzheng(); 
            
if(ss!="ok"
            

                MessageBox(ss); 
                
return
            }
 
            Random random 
= new Random(); 
            
int rand = random.Next(01,99); 
            filename 
= DateTime.Now.ToString("yyMMddhhmmss")+rand; 
            path 
= Server.MapPath(""+ "/photo/" + filename + yanzhenggeshi; 
            FileUpload1.PostedFile.SaveAs(path); 
            image 
= System.Drawing.Image.FromFile(path); 
            Bitmap bt 
= new Bitmap(image); 
            
try 
            

                bt.Save(Server.MapPath(
""+ "/photo/" + filename + yanzhenggeshi, ImageFormat.Jpeg); 
                
this.Button1.Enabled = false
                
this.Button2.Enabled = false
            }
 
            
catch(Exception ) 
            
{} 
            MessageBox(
"上传ok!"); 
            
this.Button1.Enabled = true
            
this.Button2.Enabled = true
        }
 
        
//上传至数据库 
        protected void Button2_Click(object sender, EventArgs e) 
        

            
string ss = yanzheng(); 
            
if (ss != "ok"
            

                MessageBox(ss); 
                
return
            }
 
            System.IO.Stream filestream 
= FileUpload1.PostedFile.InputStream; 
            
int filelength = FileUpload1.PostedFile.ContentLength; 
            
byte[] file = new byte[filelength];     
            filestream.Read(file, 
0, filelength);  //读取流 
            string up = upload(file); 
            
if (up == "ok"
            

                MessageBox(
"上传ok!"); 
            }
 
            
else 
            

                MessageBox(up); 
            }
 
        }
 
        
//插入图片 
        private string upload(object file) 
        

            SqlConnection con 
= new SqlConnection(url); 
            
string sql = "insert into photo(img) values(@img)"
            
string msg = ""
            
try 
            

                SqlCommand cmd 
= new SqlCommand(sql, con); 
                con.Open(); 
                cmd.Parameters.AddWithValue(
"@img",file); 
                
int count = cmd.ExecuteNonQuery(); 
                
if (count > 0
                

                    msg 
= "ok"
                    
return msg; 
                }
 
                
else 
                

                    msg
="error"
                    
return msg; 
                }
 
                con.Close(); 
            }
 
            
catch (Exception ex) 
            

                msg
=ex.Message.ToString(); 
                
return msg; 
            }
 
        }
 
        
//验证文件 
        private string yanzheng() 
        

            
string ss = ""
            yanzhenggeshi 
= Path.GetExtension(FileUpload1.PostedFile.FileName).ToUpper(); 
            
if (yanzhenggeshi == "" || yanzhenggeshi==null
            

                ss 
="请选择要上传的文件"
                
return ss; 
            }
 
            
if (yanzhenggeshi != ".JPG" && yanzhenggeshi != ".GIF"
            

                ss 
= "格式不正确"
                
return ss; 
            }
 
            
if (FileUpload1.PostedFile.ContentLength > 1048576//不能大于1M 
            
                ss 
= "图片不能大于1M"
                
return ss; 
            }
 
            
else 
            

                ss 
= "ok"
            }
 
            
return ss; 
        }
 
        
//弹出对话框 
        private void MessageBox(string msg) 
        

            Response.Write(
"<script language='javascript'>alert('" + msg + "')</script>"); 
        }
 
        
//显示图片 
        protected void Button3_Click(object sender, EventArgs e) 
        

            
string id = this.DropDownList1.SelectedValue.ToString(); 
            SqlConnection con 
= new SqlConnection(url); 
            
string sql = " select img from photo where id = '"+id+"'"
            SqlCommand cmd 
= new SqlCommand(sql,con); 
            con.Open(); 
            SqlDataReader dr 
= cmd.ExecuteReader(); 
            
if(dr.Read()) 
            

                Response.Clear(); 
                Response.BinaryWrite((
byte[])dr["img"]); 
            }
 
        }
 
        
//绑定图片列表框 
        private void bandlist() 
        

            SqlConnection con 
= new SqlConnection(url); 
            DataSet ds 
= new DataSet(); 
            
try 
            

                SqlDataAdapter dt 
= new SqlDataAdapter("select id from photo", con); 
                con.Open(); 
                dt.Fill(ds); 
                
this.DropDownList1.DataSource = ds; 
                
this.DropDownList1.DataValueField = "id"
                
this.DataBind(); 
            }
catch(Exception ex) 
            

                MessageBox(ex.Message.ToString()); 
            }
 
            con.Close(); 
        }
 
    }
 
}
 

//SQL---数据表 
//if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[photo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) 
//drop table [dbo].[photo] 
//GO 

//CREATE TABLE [dbo].[photo] ( 
//    [id] [int] IDENTITY (1001, 1) NOT NULL , 
//    [img] [image] NULL  
//) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 
//GO 


aspx文件
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication4._Default" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head runat="server"> 
    
<title>无标题页</title> 
</head> 
<body> 
    
<form id="form1" runat="server"> 
    
<div> 
     
    
</div> 
    
<asp:FileUpload ID="FileUpload1" runat="server" /> 
    
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="上传至项目文件夹"  
        Width
="136px" /> 
    
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="上传至数据库"  
        Width
="125px" /> 
    
<asp:DropDownList ID="DropDownList1" runat="server" Height="25px" Width="123px"> 
    
</asp:DropDownList> 
    
<asp:Button ID="Button3" runat="server" Height="25px" onclick="Button3_Click"  
        Text
="显示图片" Width="104px" /> 
    
</form> 
</body> 
</html>