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

C# 圖片資料庫儲存與讀取實戰指南(一):上傳儲存篇

     編輯:關於C語言

前言

本文完整示範如何在 ASP.NET WebForms 環境中實作圖片上傳、二進位儲存至 SQL Server、DataGrid 列表顯示與動態圖片瀏覽功能。

資料庫準備

在 SQL Server 2000 的 pubs 資料庫建立 ImageStore 資料表:


CREATE TABLE ImageStore (
    ImgID INT IDENTITY(1,1) PRIMARY KEY,
    ImageData IMAGE,                    -- 或 varbinary(MAX) (SQL 2005+)
    ImageContentType VARCHAR(50),       -- MIME 類型
    ImageDescription VARCHAR(200),      -- 描述
    ImageSize BIGINT                    -- 檔案大小
)

前端頁面:processImage.aspx


<%@ Page Language="c#" Codebehind="processImage.aspx.cs" AutoEventWireup="false" Inherits="imageProcess.imageProcess" %>



    圖片上傳管理


後端程式碼:processImage.aspx.cs


using System;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;

namespace imageProcess
{
    public class imageProcess : System.Web.UI.Page
    {
        protected HtmlInputFile File1;
        protected TextBox txtDescript;
        protected DataGrid DG_Persons;
        protected Button btnUpload;

        private void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) DataGridBind();
        }

        // 重新繫結 DataGrid
        private void DataGridBind()
        {
            string connStr = "server=.;database=pubs;uid=sa;pwd=;";
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(
                    "SELECT ImgID, ImageContentType, ImageSize, ImageData FROM ImageStore", conn);
                DG_Persons.DataSource = cmd.ExecuteReader();
                DG_Persons.DataBind();
            }
        }

        // 上傳按鈕點擊事件
        private void btnUpload_Click(object sender, EventArgs e)
        {
            string connStr = "server=.;database=pubs;uid=sa;pwd=;";
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                
                // 1. 讀取上傳檔案為位元組陣列
                FileStream fs = File.Open(File1.PostedFile.FileName, FileMode.Open);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, (int)fs.Length);
                fs.Close();

                // 2. 參數化 INSERT 指令
                string sql = @"INSERT INTO ImageStore 
                    (ImageData, ImageContentType, ImageDescription, ImageSize) 
                    VALUES (@Image, @FileType, @FileDesc, @FileSize)";
                
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.Add("@Image", System.Data.SqlDbType.Image, buffer.Length).Value = buffer;
                    cmd.Parameters.Add("@FileType", System.Data.SqlDbType.VarChar, 50).Value = File1.PostedFile.ContentType;
                    cmd.Parameters.Add("@FileDesc", System.Data.SqlDbType.VarChar, 200).Value = txtDescript.Text;
                    cmd.Parameters.Add("@FileSize", System.Data.SqlDbType.BigInt).Value = File1.PostedFile.ContentLength;
                    
                    cmd.ExecuteNonQuery();
                }
            }
            
            // 3. 重新整理列表
            DataGridBind();
        }

        // 產生動態圖片 URL
        protected string FormatURL(object imgId)
        {
            return "ReadImage.aspx?id=" + imgId.ToString();
        }
    }
}

關鍵技術總結

環節核心 API/技術注意事項
檔案上傳HtmlInputFile / File1.PostedFileForm 必須 enctype="multipart/form-data"
二進位讀取FileStream + byte[]大檔案建議分塊讀取避免 OOM
資料庫儲存SqlParameter + SqlDbType.Image參數化查詢防注入,Image 型別已棄用建議 varbinary(MAX)
動態圖片顯示Image.ImageUrl 指向 .aspx 處理器分離圖片輸出邏輯,支援快取/權限控制
DataGrid 模板TemplateColumn + DataBinder.Eval靈活控制每欄顯示邏輯

下篇預告

下一篇將實作 ReadImage.aspx 處理器,從資料庫讀取二進位資料並正確輸出圖片 HTTP 回應,完成完整閉環。

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