เราจะมาใช้ asp.net upload รูปภาพเข้าไปเก็บไว้ใน database กันนะครับ

เริ่มต้นโดยสร้าง Table บนฐานข้อมูลก่อนตามรูป หรือใช้คำสั่ง SQL ด้านล่างก็ได้ครับ

Table

CREATE TABLE [dbo].[PictureTable1](
	[ImageID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
	[Title] [nvarchar](50) NOT NULL,
	[DateAdded] [datetime] NOT NULL,
	[MIMEType] [nvarchar](50) NOT NULL,
	[Image] [image] NOT NULL
)

จากนั้นออกสร้างฟอร์มสำหรับ upload ข้อมูลด้วย Visual Studio 2008 ดังนี้

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

<!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>Upload Image</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>
            ตัวอย่างการ Upload รูปด้วย ASP.NET</h2>
        <table>
            <tr>
                <td>
                    Title
                </td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Image
                </td>
                <td>
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;
                </td>
                <td>
                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload" />
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    <asp:Label ID="Label1" runat="server"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Code behind

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

public partial class UploadPicture : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(TextBox1.Text.Trim()) && FileUpload1.HasFile)
        {
            string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName).ToLower();
            string extension = Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower();
            string mimeType = FileUpload1.PostedFile.ContentType;
            switch (extension)
            {
                case ".gif":
                    mimeType = "image/gif";
                    break;
                case ".jpg":
                case ".jpeg":
                case ".jpe":
                    mimeType = "image/jpeg";
                    break;
                case ".png":
                    mimeType = "image/png";
                    break;
                default:
                    //Invalid file type uploaded
                    Label1.Text = "ไม่สามารถ upload ได้ (ระบบสามารถรับไฟล์นามสกุล gif, jpg, jpeg, jpe, png เท่านั้น)..";
                    return;
            }
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_TestConnection"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText = "INSERT INTO [PictureTable] ([Title], [MIMEType], [Image],[DateAdded]) VALUES (@Title, @MIMEType, @ImageData,@DateAdded)";

                cmd.Parameters.AddWithValue("@Title", TextBox1.Text.Trim());
                cmd.Parameters.AddWithValue("@MIMEType", mimeType);
                cmd.Parameters.AddWithValue("@DateAdded", DateTime.Now);
                byte [] imageBytes = new byte[FileUpload1.PostedFile.InputStream.Length];
                FileUpload1.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
                cmd.Parameters.AddWithValue("@ImageData", imageBytes);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                Label1.Text = "Upload เรียบร้อย..";
            }
        }
        else
        {
            Label1.Text = "";
            if (string.IsNullOrEmpty(TextBox1.Text.Trim())) Label1.Text += "กรุณาใส่ Title รูป.. <br />";
            if (!FileUpload1.HasFile) Label1.Text += "กรุณาเลือกไฟล์ที่จะ upload ด้วยครับ..";
        }
    }
}

การแสดงผล Binary Data

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["ImageId"]))
        {
            int imageId = Convert.ToInt32(Request.QueryString["ImageId"]);
            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_TestConnection"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandText = "SELECT [MIMEType], [Image] FROM [PictureTable] WHERE [ImageID] = @ImageId";
                cmd.Parameters.AddWithValue("@ImageID", imageId);
                con.Open();
                SqlDataReader rd = cmd.ExecuteReader();
                if (rd.Read())
                {
                    Response.ContentType = rd["MIMEType"].ToString();
                    Response.BinaryWrite((byte[])rd["Image"]);
                }
                rd.Close();
                con.Close();
            }
        }
    }