[ASP.NET]圖片檔案上傳儲存在資料庫中

圖片檔案上傳;檔案儲存在資料庫中,並不需額外資料夾儲存。

上傳圖片頁,conn 可以改為自已的資料庫連線。

Private Conn As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("SiteSqlServer"))

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim UpFile As HttpPostedFile = File1.PostedFile
        Dim imageStream As Stream = UpFile.InputStream
        Dim fileLength As Integer = UpFile.ContentLength  '取得檔案尺寸
        Dim buffer(fileLength) As Byte
        imageStream.Read(buffer, 0, fileLength)           '讀取檔案內容並存至buffer陣列
        imageStream.Close()

        Conn.Open()
        Dim sqlInsert As String = "insert into FileUpload(pic,picType) values (@image,@type)"
        Dim cmd As SqlCommand = New SqlCommand(sqlInsert, Conn)

        cmd.Parameters.Add(New SqlParameter("@image", SqlDbType.Image))   '宣告
        cmd.Parameters.Add(New SqlParameter("@type", SqlDbType.NVarChar, 50))
        cmd.Parameters("@image").Value = buffer
        cmd.Parameters("@type").Value = UpFile.ContentType 'ContentType為圖片副檔名

        Dim dr = cmd.ExecuteNonQuery()
    End Sub


 讀取出來的網頁

    Private Conn As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("SiteSqlServer"))

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Conn.Open()
        Dim sqlInsert As String = "select * from FileUpload where picID=" & Request("ID")
        Dim cmd As SqlCommand = New SqlCommand(sqlInsert, Conn)
        Dim dr As SqlDataReader = cmd.ExecuteReader
        dr.Read()

        Response.ContentType = dr("picType")
        Response.BinaryWrite(dr("pic"))

    End Sub