1. 程式人生 > >ASP.NET_上傳圖片,並把圖片路徑儲存到資料庫中

ASP.NET_上傳圖片,並把圖片路徑儲存到資料庫中

//html頁面程式碼

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>


<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    //asp:Image 控制元件
        <div>
            <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/lmage_4.jpeg" Width="150" Height="170"/>  
        </div>


        <div>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Label ID="lbl" runat="server" Text="Label"></asp:Label>
            <asp:Button ID="Button1" runat="server" Text="上傳" OnClick="Button1_Click" />
        </div>
    </form>
</body>

</html>

============================================================================

//後臺程式碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;




public partial class Default2 : System.Web.UI.Page
{
    DBHelper dbhelper = new DBHelper();//我是用Web.config和類寫的連線,這處不要複製,建議你們自己寫連線
    int id = 0;


    protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        bool bok = false;//預設為false
        string path = Server.MapPath("Images");//儲存資料夾路徑
        if(this.FileUpload1.HasFile)//檢測是否有上傳檔案
        {
            string file = System.IO.Path.GetExtension(this.FileUpload1.FileName).ToLower();//獲取資料夾下的檔案路徑
            string[] allow = new string[] { ".png", ".jpg", ".gif", ".bmp", ".jpeg" };//字尾名陣列


            foreach(string s in allow)//讀取字尾名陣列
            {
                if (s == file) //如果符合數組裡的型別
                {
                    bok = true;//bool值為true
                }
            }


            if (bok)//如果為true
            {
                try
                {
                    this.FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);//上傳檔案
                    this.lbl.Text = "檔案" + FileUpload1.FileName + "上傳成功!";                   
                }
                catch (Exception ex)
                {
                    this.lbl.Text = "檔案上傳失敗!" + ex.Message;
                }
            }
            else 
            {
                this.lbl.Text = "上傳的圖片格式不正確:只能上傳.png,jpg,.gif,.bmp,.jpeg";
            }
        }

        this.Image1.ImageUrl = this.Request.ApplicationPath + ("Images" + FileUpload1.FileName);//把上傳的圖片賦給Image1路徑

        Update();

    }


    void Update()//把上傳圖片路徑儲存到資料庫中
    {
        dbhelper.connection.Open();
        int id = Convert.ToInt32(Request.QueryString["Id"]);//獲取資料庫Logins表中的Id
        string URL = "~/Images/" + this.FileUpload1.FileName;//檔案路徑名
        string sql = string.Format("UPDATE Logins SET Image='{0}' WHERE Id={1}", URL, id);//SQL語句
        SqlCommand command = new SqlCommand(sql, dbhelper.connection);//定義SQL執行語句
        command.ExecuteNonQuery();//執行SQL語句


        dbhelper.connection.Close();
        command.Dispose();//釋放快取
  
    }


}