【问题标题】:Uploading files to SQL Server 2012 with ASP.NET/VB.NET使用 ASP.NET/VB.NET 将文件上传到 SQL Server 2012
【发布时间】:2013-04-09 09:35:19
【问题描述】:

我按照教程运行了以下代码,没有任何错误。文件“上传”,但没有数据插入到我的 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

【问题讨论】:

  • 1) 检查您的连接字符串,我看到您从配置中获取信息,但随后忽略它并使用另一个硬编码的连接字符串。 2)这无济于事,而是优化:您不应该同时调用 conn.Close() 和 conn.Dispose() , Cl​​ose 方法在内部调用 Dispose。
  • @IhorDeyneka 我删除了 conn.dispose 并更改了这些行:Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString() Dim conn As New SqlConnection(strConnString),没有错误但仍然不起作用
  • 你调试了吗? cmd.ExecuteNonQuery() 执行成功还是发生异常?在调试期间,在执行 ExecuteNonQuery 之前检查 cmd 的所有重要属性
  • 无一例外,一切正常,只是没有数据放入db表!
  • @IhorDeyneka 添加了有问题的调试信息!

标签: asp.net vb.net file-upload sql-server-2012 varbinarymax


【解决方案1】:

我创建了空数据库并添加了表 content 就像你一样,我使用的代码几乎和你一样,它工作得很好。

再次,如果没有出现异常,请检查您的连接字符串,看看是否将行添加到连接字符串中指定的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]

【讨论】:

  • 不知道怎么回事,试了下代码还是一样..i.imgur.com/zKqjJ0u.jpg
  • 内容大小是多少?我以前没看过那个专栏。
  • 啊,我刚刚添加了,所以我稍后会在其中编码文件的大小,但目前它没有被使用。
  • 但它可以为空吗?如果不是,那么那个 SQL 脚本应该会崩溃,你应该得到一个异常
  • 是的,它设置为允许 NULL 以 'bit' 作为值。
【解决方案2】:

我在寻找示例时遇到了这篇文章。我使用了您发布的示例代码并遇到了同样的问题。我发现并解决了以下问题并使其正常工作:

  • 我创建了如图所示的 db 表。 nchar(5) 的 content_type 是第一个问题,因为您插入了太大的“application/vnd.ms-word”之类的内容。
  • 下一个错误是因为我没有将 content_id 定义为标识列,并且因为它没有在插入语句中列出,所以它失败了。
  • 接下来我遇到了一个错误,因为我的 db 用户没有插入权限。
  • 最大的问题是返回消息始终是成功消息,因为即使 InsertUpdateData 函数捕获错误,它也没有通知调用代码。这让我觉得事情还好。哦!在 ExecuteNonQuery 上使用断点可以让我看到错误。

希望能帮助下一个路过的人......

【讨论】:

    猜你喜欢
    • 2013-03-17
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多