asp.net圖片上傳 ----上傳至數據庫---上傳至項目文件夾

  1. using System;
  2. using System.Collections;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Web;
  6. using System.Web.Security;
  7. using System.Web.UI;
  8. using System.Web.UI.HtmlControls;
  9. using System.Web.UI.WebControls;
  10. using System.Web.UI.WebControls.WebParts;
  11. using System.Data.SqlClient;
  12. using System.IO;
  13. using System.Drawing;
  14. using System.Drawing.Imaging;
  15. namespace WebApplication4
  16. {
  17.     public partial class _Default : System.Web.UI.Page
  18.     {
  19.         string filename = "";      //文件名
  20.         string yanzhenggeshi = ""//驗證文件擴展名
  21.         string path = "";          //上傳的文件路徑
  22.         System.Drawing.Image image; //畫圖
  23.         string url = "server=.;uid=sa;password=12345;database=pubs"
  24.         protected void Page_Load(object sender, EventArgs e)
  25.         {
  26.             if (!IsPostBack)
  27.             {
  28.                 bandlist();
  29.             }
  30.         }
  31.         //上傳至項目文件夾photo
  32.         protected void Button1_Click(object sender, EventArgs e)
  33.         {
  34.             string ss = yanzheng();
  35.             if(ss!="ok")
  36.             {
  37.                 MessageBox(ss);
  38.                 return;
  39.             }
  40.             Random random = new Random();
  41.             int rand = random.Next(01,99);
  42.             filename = DateTime.Now.ToString("yyMMddhhmmss")+rand;
  43.             path = Server.MapPath("") + "/photo/" + filename + yanzhenggeshi;
  44.             FileUpload1.PostedFile.SaveAs(path);
  45.             image = System.Drawing.Image.FromFile(path);
  46.             Bitmap bt = new Bitmap(image);
  47.             try
  48.             {
  49.                 bt.Save(Server.MapPath("") + "/photo/" + filename + yanzhenggeshi, ImageFormat.Jpeg);
  50.                 this.Button1.Enabled = false;
  51.                 this.Button2.Enabled = false;
  52.             }
  53.             catch(Exception )
  54.             {}
  55.             MessageBox("上傳ok!");
  56.             this.Button1.Enabled = true;
  57.             this.Button2.Enabled = true;
  58.         }
  59.         //上傳至數據庫
  60.         protected void Button2_Click(object sender, EventArgs e)
  61.         {
  62.             string ss = yanzheng();
  63.             if (ss != "ok")
  64.             {
  65.                 MessageBox(ss);
  66.                 return;
  67.             }
  68.             System.IO.Stream filestream = FileUpload1.PostedFile.InputStream;
  69.             int filelength = FileUpload1.PostedFile.ContentLength;
  70.             byte[] file = new byte[filelength];    
  71.             filestream.Read(file, 0, filelength);  //讀取流
  72.             string up = upload(file);
  73.             if (up == "ok")
  74.             {
  75.                 MessageBox("上傳ok!");
  76.             }
  77.             else
  78.             {
  79.                 MessageBox(up);
  80.             }
  81.         }
  82.         //插入圖片
  83.         private string upload(object file)
  84.         {
  85.             SqlConnection con = new SqlConnection(url);
  86.             string sql = "insert into photo(img) values(@img)";
  87.             string msg = "";
  88.             try
  89.             {
  90.                 SqlCommand cmd = new SqlCommand(sql, con);
  91.                 con.Open();
  92.                 cmd.Parameters.AddWithValue("@img",file);
  93.                 int count = cmd.ExecuteNonQuery();
  94.                 if (count > 0)
  95.                 {
  96.                     msg = "ok";
  97.                     return msg;
  98.                 }
  99.                 else
  100.                 {
  101.                     msg="error";
  102.                     return msg;
  103.                 }
  104.                 con.Close();
  105.             }
  106.             catch (Exception ex)
  107.             {
  108.                 msg=ex.Message.ToString();
  109.                 return msg;
  110.             }
  111.         }
  112.         //驗證文件
  113.         private string yanzheng()
  114.         {
  115.             string ss = "";
  116.             yanzhenggeshi = Path.GetExtension(FileUpload1.PostedFile.FileName).ToUpper();
  117.             if (yanzhenggeshi == "" || yanzhenggeshi==null)
  118.             {
  119.                 ss ="請選擇要上傳的文件";
  120.                 return ss;
  121.             }
  122.             if (yanzhenggeshi != ".JPG" && yanzhenggeshi != ".GIF")
  123.             {
  124.                 ss = "格式不正確";
  125.                 return ss;
  126.             }
  127.             if (FileUpload1.PostedFile.ContentLength > 1048576) //不能大於1M
  128.             {
  129.                 ss = "圖片不能大於1M";
  130.                 return ss;
  131.             }
  132.             else
  133.             {
  134.                 ss = "ok";
  135.             }
  136.             return ss;
  137.         }
  138.         //彈出對話框
  139.         private void MessageBox(string msg)
  140.         {
  141.             Response.Write("<script language='javascript'>alert('" + msg + "')</script>");
  142.         }
  143.         //顯示圖片
  144.         protected void Button3_Click(object sender, EventArgs e)
  145.         {
  146.             string id = this.DropDownList1.SelectedValue.ToString();
  147.             SqlConnection con = new SqlConnection(url);
  148.             string sql = " select img from photo where id = '"+id+"'";
  149.             SqlCommand cmd = new SqlCommand(sql,con);
  150.             con.Open();
  151.             SqlDataReader dr = cmd.ExecuteReader();
  152.             if(dr.Read())
  153.             {
  154.                 Response.Clear();
  155.                 Response.BinaryWrite((byte[])dr["img"]);
  156.             }
  157.         }
  158.         //綁定圖片列表框
  159.         private void bandlist()
  160.         {
  161.             SqlConnection con = new SqlConnection(url);
  162.             DataSet ds = new DataSet();
  163.             try
  164.             {
  165.                 SqlDataAdapter dt = new SqlDataAdapter("select id from photo", con);
  166.                 con.Open();
  167.                 dt.Fill(ds);
  168.                 this.DropDownList1.DataSource = ds;
  169.                 this.DropDownList1.DataValueField = "id";
  170.                 this.DataBind();
  171.             }catch(Exception ex)
  172.             {
  173.                 MessageBox(ex.Message.ToString());
  174.             }
  175.             con.Close();
  176.         }
  177.     }
  178. }
  179. //SQL---數據表
  180. //if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[photo]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
  181. //drop table [dbo].[photo]
  182. //GO
  183. //CREATE TABLE [dbo].[photo] (
  184. //    [id] [int] IDENTITY (1001, 1) NOT NULL ,
  185. //    [img] [image] NULL 
  186. //) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  187. //GO

 

aspx文件

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication4._Default" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" >
  4. <head runat="server">
  5.     <title>無標題頁</title>
  6. </head>
  7. <body>
  8.     <form id="form1" runat="server">
  9.     <div>
  10.     
  11.     </div>
  12.     <asp:FileUpload ID="FileUpload1" runat="server" />
  13.     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="上傳至項目文件夾" 
  14.         Width="136px" />
  15.     <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="上傳至數據庫" 
  16.         Width="125px" />
  17.     <asp:DropDownList ID="DropDownList1" runat="server" Height="25px" Width="123px">
  18.     </asp:DropDownList>
  19.     <asp:Button ID="Button3" runat="server" Height="25px" onclick="Button3_Click" 
  20.         Text="顯示圖片" Width="104px" />
  21.     </form>
  22. </body>
  23. </html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章