簡體   English   中英

使用ASP.NET / VB.NET將文件上載到SQL Server 2012

[英]Uploading files to SQL Server 2012 with ASP.NET/VB.NET

我按照教程運行了以下代碼,沒有任何錯誤。 文件“上傳”,但沒有數據插入我的SQL Server表。

應將數據插入content表中。

內容表:

在此輸入圖像描述

Document.aspx

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

Partial Class Documents
    Inherits System.Web.UI.Page

    Protected Sub btnUploadContent_Click(sender As Object, e As EventArgs) Handles btnUploadContent.Click

        Dim filePath As String = FileUpload.PostedFile.FileName

        Dim filename As String = Path.GetFileName(filePath)

        Dim ext As String = Path.GetExtension(filename)

        Dim contenttype As String = String.Empty



        Select Case ext

            Case ".doc"

                contenttype = "application/vnd.ms-word"

                Exit Select

            Case ".docx"

                contenttype = "application/vnd.ms-word"

                Exit Select

            Case ".xls"

                contenttype = "application/vnd.ms-excel"

                Exit Select

            Case ".xlsx"

                contenttype = "application/vnd.ms-excel"

                Exit Select

            Case ".jpg"

                contenttype = "image/jpg"

                Exit Select

            Case ".png"

                contenttype = "image/png"

                Exit Select

            Case ".gif"

                contenttype = "image/gif"

                Exit Select

            Case ".pdf"

                contenttype = "application/pdf"

                Exit Select

        End Select

        If contenttype <> String.Empty Then

            Dim fs As Stream = FileUpload.PostedFile.InputStream

            Dim br As New BinaryReader(fs)

            Dim bytes As Byte() = br.ReadBytes(fs.Length)



            'insert the file into database

            Dim strQuery As String = "INSERT INTO content (content_name, content_type, content_file) VALUES (@Name, @ContentType, @Data)"

            Dim cmd As New SqlCommand(strQuery)

            cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename

            cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value() = contenttype

            cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes

            InsertUpdateData(cmd)

            lblMessage.ForeColor = System.Drawing.Color.Green

            lblMessage.Text = "File Uploaded Successfully"

        Else

            lblMessage.ForeColor = System.Drawing.Color.Red

            lblMessage.Text = "File format not recognised." + " Upload Image/Word/PDF/Excel formats"

        End If

    End Sub




    Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean

        Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()

        Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")

        cmd.CommandType = CommandType.Text

        cmd.Connection = conn

        Try

            conn.Open()

            cmd.ExecuteNonQuery()

            Return True

        Catch ex As Exception

            Response.Write(ex.Message)

            Return False

        Finally

            conn.Close()

            conn.Dispose()

        End Try

    End Function

End Class

誰能告訴我發生了什么事?

編輯: 調試斷點@ InsertUpdateData(cmd)

        SqlDbType.Binary    Binary {1}  System.Data.SqlDbType
+       bytes   {Length=4136752}    Byte()
+       cmd {System.Data.SqlClient.SqlCommand}  System.Data.SqlClient.SqlCommand
+       cmd.Parameters  {System.Data.SqlClient.SqlParameterCollection}  System.Data.SqlClient.SqlParameterCollection

我已經創建了空數據庫並添加了表格內容 ,就像你一樣,我使用的代碼幾乎和你一樣,並且工作正常。

同樣,如果沒有異常發生,請檢查您的連接字符串,看看是否已將行添加到連接字符串中指定的db中的表中。 這是我的代碼(工作正常),有點修改你的:

Imports System.Data.SqlClient
Imports System.IO

Public Class _Default
Inherits System.Web.UI.Page

Protected Sub btnUploadContent_Click(sender As Object, e As EventArgs) Handles btnTest1.Click

    Dim fs As Stream = FileUpload.PostedFile.InputStream

    Dim br As New BinaryReader(fs)

    Dim bytes As Byte() = br.ReadBytes(fs.Length)


    'insert the file into database

    Dim strQuery As String = "INSERT INTO content (content_name, content_type, content_file) VALUES (@Name, @ContentType, @Data)"

    Dim cmd As New SqlCommand(strQuery)

    cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = "filename"

    cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value() = "jpg"

    cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes

    InsertUpdateData(cmd)

End Sub




Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean

    Dim conn As New SqlConnection("Data Source=(local);Initial Catalog=test;Integrated Security=True;")

    cmd.CommandType = CommandType.Text

    cmd.Connection = conn

    Try

        conn.Open()

        cmd.ExecuteNonQuery()

        Return True

    Catch ex As Exception

        Response.Write(ex.Message)

        Return False

    Finally

        conn.Close()

        conn.Dispose()

    End Try

End Function

End Class

我添加了SQL樣本來測試DB:

 INSERT INTO [master_db].[dbo].[content]
       ([content_name]
       ,[content_type]
       ,[content_file])
 VALUES
       ('test'
       ,'png'
       ,0x111111111111111)

 SELECT * FROM [master_db].[dbo].[content]

我看到這個帖子正在尋找一個例子。 我使用了您發布的示例代碼並遇到了同樣的問題。 我發現並解決了以下問題並使其正常工作:

  • 我創建了db表,如圖所示。 nchar(5)的content_type是你插入像“application / vnd.ms-word”這樣太大的第一個問題。
  • 下一個錯誤是因為我沒有將content_id定義為標識列,因為它沒有在insert語句中列出,所以它失敗了。
  • 接下來我有一個錯誤,因為我的db用戶沒有插入權限。
  • 最大的問題是返回消息始終是成功消息,因為即使InsertUpdateData函數捕獲錯誤,它也沒有通知調用代碼。 這讓我覺得事情沒問題。 衛生署! 在ExecuteNonQuery上使用斷點允許我查看錯誤。

希望能幫助下一個停下來的人....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM