使用VB.Net + Image下载和从SQL下载图像不正确

时间:2014-01-07 10:45:10

标签: sql vb.net image-processing

Imports System
Imports System.Data.SqlClient
Imports System.IO

Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        ' Read the file and convert it to Byte Array
        Dim filePath As String = FileUpload1.PostedFile.FileName
        Dim filename As String = Path.GetFileName(filePath)
        Dim ext As String = Path.GetExtension(filename)
        Dim contenttype As String = String.Empty

        'Set the contenttype based on File Extension
        Select Case ext
            Case ".jpg"
                contenttype = "image/jpg"
                Exit Select
            Case ".png"
                contenttype = "image/png"
                Exit Select
        End Select
        If contenttype <> String.Empty Then
            Dim fs As Stream = FileUpload1.PostedFile.InputStream
            Dim br As New BinaryReader(fs)
            Dim bytes() As Byte = br.ReadBytes(fs.Length)
            lblMessage.Text = bytes.ToString 'System.Text.Encoding.Unicode.GetString(bytes)
            'insert the file into database
            Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
            Dim con As New SqlConnection(strConnString)

            Try
                con.Open()
                Dim strQuery As String = "insert into uploadedImages (Name, ContentType, Data) values ('" & filename & "','" & contenttype & "','"
                Dim bytesLength As Integer = bytes.Length - 1
                For i As Integer = 0 To bytesLength
                    strQuery = strQuery & bytes(i)
                Next
                strQuery = strQuery & "')"
                Dim cmd As New SqlCommand(strQuery)
                cmd.CommandType = CommandType.Text
                cmd.Connection = con

                cmd.ExecuteNonQuery()

            Catch ex As Exception
                Response.Write(ex.Message)

            Finally
                con.Close()
                con.Dispose()
            End Try

            ' InsertUpdateData(cmd)
            lblMessage.ForeColor = System.Drawing.Color.Green
            lblMessage.Text = "File Uploaded Successfully" '& System.Text.ASCIIEncoding.ASCII.GetString(bytes)
        Else
            lblMessage.ForeColor = System.Drawing.Color.Red
            lblMessage.Text = "File format not recognised." & " Upload Image JPG or PNG formats"
        End If
    End Sub

    Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
        Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
        Dim con As New SqlConnection(strConnString)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        Try
            con.Open()
            cmd.ExecuteNonQuery()
            Return True
        Catch ex As Exception
            Response.Write(ex.Message)
            Return False
        Finally
            con.Close()
            con.Dispose()
        End Try
    End Function

    ' code to retrieve image
    Public Function GetData(ByVal cmd As SqlCommand) As DataTable
        Dim dt As New DataTable
        Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString()
        Dim con As New SqlConnection(strConnString)
        Dim sda As New SqlDataAdapter
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        Try
            con.Open()
            sda.SelectCommand = cmd
            sda.Fill(dt)
            Return dt
        Catch ex As Exception
            Response.Write(ex.Message)
            Return Nothing
        Finally
            con.Close()
            sda.Dispose()
            con.Dispose()
        End Try
    End Function

    Protected Sub download(ByVal dt As DataTable)
        Dim bytes As String = CType(dt.Rows(0)("Data"), String)
        Response.Buffer = True
        Response.Charset = ""
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Response.ContentType = dt.Rows(0)("ContentType").ToString()
        Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows(0)("Name").ToString())
        ' convert a string to a byte array
        Dim encoding As New System.Text.UTF8Encoding()

        Response.BinaryWrite(encoding.GetBytes(dt.Rows(0)("Data"))) 
        Response.Flush()
        Response.End()
    End Sub

    Protected Sub btn_download_Click(sender As Object, e As EventArgs) Handles btn_download.Click
        Dim strQuery As String = "select Name, ContentType, Data from uploadedImages where id=12"
        Dim cmd As SqlCommand = New SqlCommand(strQuery)
        cmd.Parameters.Add("12", SqlDbType.Int).Value = 1
        Dim dt As DataTable = GetData(cmd)
        If dt IsNot Nothing Then
            download(dt)
        End If
    End Sub
End Class
  

图像下载但文件已损坏,我认为问题是从数据库中检索字符串并将其转换为字节...感谢任何帮助

0 个答案:

没有答案