首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 圖片上傳至 SQL Server 資料庫完整範例

     編輯:關於ASP.NET

利用 HtmlInputFile 控制項接收 multipart/form-data 上傳,讀取 HttpPostedFile.InputStream 為位元組陣列,以參數化命令寫入 image 型別欄位;讀取時設定 Response.ContentType 並用 Response.OutputStream.Write 輸出二進位資料。

資料表結構

CREATE TABLE ImageStore (
    ImageID INT IDENTITY(1,1) PRIMARY KEY,
    ImageData IMAGE NULL,
    ImageContentType VARCHAR(50) NULL,
    ImageDescription VARCHAR(200) NULL,
    ImageSize INT NULL
)

上傳頁面 (UpLoadImage.aspx + .cs)

// 前端
<form enctype="multipart/form-data" runat="server">
    <input type="file" id="UP_FILE" runat="server" />
    <asp:TextBox id="txtDescription" runat="server" />
    <asp:Button OnClick="Button_Submit" Text="上傳" runat="server" />
</form>

// 後端
protected void Button_Submit(object sender, EventArgs e)
{
    HttpPostedFile file = UP_FILE.PostedFile;
    if (file.ContentLength == 0) { /* 提示 */ return; }

    byte[] buffer = new byte[file.ContentLength];
    file.InputStream.Read(buffer, 0, file.ContentLength);

    using (SqlConnection conn = new SqlConnection(connStr))
    using (SqlCommand cmd = new SqlCommand(
        "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) " +
        "VALUES (@Image, @Type, @Desc, @Size)", conn))
    {
        cmd.Parameters.Add("@Image", SqlDbType.Image, buffer.Length).Value = buffer;
        cmd.Parameters.Add("@Type", SqlDbType.VarChar, 50).Value = file.ContentType;
        cmd.Parameters.Add("@Desc", SqlDbType.VarChar, 200).Value = txtDescription.Text;
        cmd.Parameters.Add("@Size", SqlDbType.Int).Value = file.ContentLength;
        conn.Open(); cmd.ExecuteNonQuery();
    }
}

顯示頁面 (ReadImage.aspx)

int id = Convert.ToInt32(Request.QueryString["ImgID"]);
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM ImageStore WHERE ImageID=@id", conn))
{
    cmd.Parameters.AddWithValue("@id", id);
    conn.Open();
    using (SqlDataReader dr = cmd.ExecuteReader())
    {
        if (dr.Read())
        {
            Response.ContentType = dr["ImageContentType"].ToString();
            Response.OutputStream.Write((byte[])dr["ImageData"], 0, (int)dr["ImageSize"]);
            Response.End();
        }
    }
}

前端以 <img src="ReadImage.aspx?ImgID=1" /> 即可顯示。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved