简体   繁体   English

使用ASP.NET / VB.NET将文件上载到SQL Server 2012

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

I followed a tutorial an ran the below code without any errors. 我按照教程运行了以下代码,没有任何错误。 The file "uploads", however no data is inserted into my SQL Server table. 文件“上传”,但没有数据插入我的SQL Server表。

Data should be inserted into the content table. 应将数据插入content表中。

Content Table: 内容表:

在此输入图像描述

Document.aspx 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

Can anyone tell me what's going on ? 谁能告诉我发生了什么事?

EDIT: Debug Breakpoint @ InsertUpdateData(cmd) : 编辑: 调试断点@ 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

I have created empty database and added table content just like you have and I used code almost the same as you and it worked fine. 我已经创建了空数据库并添加了表格内容 ,就像你一样,我使用的代码几乎和你一样,并且工作正常。

Again, if no exception occurs, please check your connection string and see whether the rows been added to the table in the db specified in connection string. 同样,如果没有异常发生,请检查您的连接字符串,看看是否已将行添加到连接字符串中指定的db中的表中。 Here is my code (which is working fine), a bit modified from yours: 这是我的代码(工作正常),有点修改你的:

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

I add sample of SQL to test on DB: 我添加了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 came across this post looking looking for an example. 我看到这个帖子正在寻找一个例子。 I used the example code you posted and had the same problem. 我使用了您发布的示例代码并遇到了同样的问题。 I found and resolved the following issues and got it working: 我发现并解决了以下问题并使其正常工作:

  • I created the db table as pictured. 我创建了db表,如图所示。 content_type of nchar(5) was the first problem since you were inserting something like "application/vnd.ms-word" which was too big. nchar(5)的content_type是你插入像“application / vnd.ms-word”这样太大的第一个问题。
  • The next error was because I had not defined the content_id to be an identity column and since it wasn't listed in the insert statement it failed. 下一个错误是因为我没有将content_id定义为标识列,因为它没有在insert语句中列出,所以它失败了。
  • Next I had an error as my db user didn't have insert privileges. 接下来我有一个错误,因为我的db用户没有插入权限。
  • The biggest problem is that the return message was always a success message because even though the InsertUpdateData function was catching errors it was not notifying the calling code. 最大的问题是返回消息始终是成功消息,因为即使InsertUpdateData函数捕获错误,它也没有通知调用代码。 This made me think things were okay. 这让我觉得事情没问题。 doh! 卫生署! Using a breakpoint on the ExecuteNonQuery allowed me to see the errors. 在ExecuteNonQuery上使用断点允许我查看错误。

Hope that helps the next person that stops by.... 希望能帮助下一个停下来的人....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM