VB.NET 网页在尝试将文件上传到数据库时被拒绝访问

VB.NET webpage gets access denied when trying to upload a file to a database

我正在尝试编写一个页面以将徽标上传到 SQL 数据库。但是,我不断收到访问被拒绝的错误。当我运行该过程时,抛出以下异常:

System.UnauthorizedAccessException: Access to the path 'C:\Users\ANDY\Pictures\Logo.PNG' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at _Default.SaveToDB(String info) in...

文件:'C:\Users\ANDY\Pictures\Logo.PNG' 在我的客户端(不是服务器)上,如果我授予每个人对该文件的完全控制权限,那么它会成功上传到远程服务器。

我不能要求我的用户更改他们上传文件的权限。

在我的测试中,我在两台电脑上试过: +我的开发电脑: - 在 vi​​sual studio 的调试模式下,效果很好 - 在同一台计算机上,如果我将它加载到 IIS 中,它会抛出上述异常,要求向我尝试上传的本地文件或文件夹授予权限。 +我的生产服务器: - 上传到生产服务器的相同文件会产生略有不同的错误。这次它想要在服务器上修改此路径的权限:c:\Windows\System32\inetsrv 我想我会尝试将对此文件夹的访问权限授予 NetworkService 帐户,但是,这似乎是一个受保护的文件夹,您无法修改System32 下文件夹的权限。您也无法将 NetworkService 帐户添加到本地管理员(我知道,我知道 - 安全性差 - 但我只是在这里进行故障排除)。

带有 SQL 服务器 2008 R2 的 IIS 6 正在托管站点。

网页代码如下:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="TestImageUpload.aspx.vb" Inherits="_Default" MasterPageFile="MasterPage.master"%>

<%@ Register Src="sideMenuControl.ascx" TagName="sideMenuControl" TagPrefix="uc1" %>

<asp:Content ID="contentHolder" ContentPlaceHolderID="ContentPlaceHolder" runat="Server"> 
    <div id="mainContent">

<div id="sidecol">
    <uc1:sideMenuControl ID="SideMenuControl1" runat="server" />

</div>
<div id="content">
    <h1>Upload your company logo here</h1>
<asp:Label ID="Label3" runat="server" Text="Select your Logo File:"></asp:Label>
                <br />
                
        <input id="FileUpload1" type="file" runat="server" />
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <br />
                <br />
                <asp:Label ID="Label1" runat="server"></asp:Label>
                <br />
                <asp:Button ID="Button1" runat="server" Text="Update my Logo" />
                <br />
                <asp:Label ID="Label2" runat="server"></asp:Label>
            </ContentTemplate>
            <Triggers>
                <asp:PostBackTrigger ControlID="Button1" />
            </Triggers>
        </asp:UpdatePanel>
      </div>      
      </div>
 </asp:Content>

VB代码文件如下:

Imports System.Data
Imports System.Collections.Generic
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports MigrateNationalTrades
Imports System.IO

Partial Class _Default
    Inherits System.Web.UI.Page

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

        If FileUpload1.Value <> "" Then
            Label1.Text = ""
            Label2.Text = "Starting upload of: " + FileUpload1.Value.ToString().Trim()
            Dim imageInfo As FileInfo = New FileInfo(FileUpload1.Value.ToString().Trim())
            Select Case (imageInfo.Extension.ToUpper())
                Case ".JPG" : SaveToDB(Me.FileUpload1.Value.Trim())
                Case ".JPEG" : SaveToDB(Me.FileUpload1.Value.Trim())
                Case ".GIF" : SaveToDB(Me.FileUpload1.Value.Trim())
                Case ".BMP" : SaveToDB(Me.FileUpload1.Value.Trim())
                Case ".PNG" : SaveToDB(Me.FileUpload1.Value.Trim())
                Case Else
                    ClientScript.RegisterClientScriptBlock(Me.GetType(), "alertMsg", "<script>alert('Error: Unknown File Type.');</script>")
            End Select
        Else
            Label1.Text = "Please cloose a file and try again"
            Label2.Text = "" + FileUpload1.Value.ToString()
        End If

    End Sub

    Private Sub SaveToDB(ByVal info As String)
        Dim objconn As SqlConnection
        objconn = New SqlConnection(ConfigurationManager.ConnectionStrings("TestConnectionString").ConnectionString)
        Dim objCom As SqlCommand
        Try
            Dim imagestream As FileStream = New FileStream(info, FileMode.Open)
            Dim data() As Byte
            ReDim data(imagestream.Length - 1)
            imagestream.Read(data, 0, imagestream.Length)
            imagestream.Close()
            objCom = New SqlCommand("insert into Logos(UserID,Logo) values (@UserID,@Logo)", objConn)
            Dim useridparameter As SqlParameter = New SqlParameter("@UserID", SqlDbType.Int)
            useridparameter.Value = "251"
            objCom.Parameters.Add(useridparameter)
            Dim logoparameter As SqlParameter = New SqlParameter("@Logo", SqlDbType.Image)
            logoparameter.Value = data
            objCom.Parameters.Add(logoparameter)
            objconn.Open()
            objCom.ExecuteNonQuery()
            objconn.Close()
            Label2.Text = "Logo uploaded successfully!"
        Catch ex As Exception
            Label1.Text = ""
            Label2.Text = "Failed: " + ex.ToString()
        End Try

    End Sub


    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        'Form.Enctype() = "multipart/form-data"
    End Sub
End Class

我很困惑为什么系统需要对正在读取以上传的文件进行写访问。也许你们可以帮助我?

试试下面这个。 fileData 是你将传递给你的 sql。

将 asp 控件更改为:

<asp:FileUpload ID="FileUpload1" runat="server" />

然后使用:

  If FileUpload1.ContentLength > 0 Then

        Dim size As Integer = FileUpload1.ContentLength
        Dim name As String = FileUpload1.FileName
        Dim position As Integer = name.LastIndexOf("\")
        name = name.Substring(position + 1)
        Dim contentType As String = FileUpload1.ContentType
        Dim fileData As Byte() = New Byte(size - 1) {}
        FileUpload1.InputStream.Read(fileData, 0, size)

    End If

非常感谢 RickJames 帮助我解决了这个难题。他很棒!这是文件上传例程的最终工作代码,在我所有的机器上测试都正常。我想这是阻止进程正常工作的完整路径,FileUpload 控件会为您处理:

网页:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="TestImageUpload.aspx.vb" Inherits="_Default" MasterPageFile="MasterPage.master"%>

<%@ Register Src="sideMenuControl.ascx" TagName="sideMenuControl" TagPrefix="uc1" %>

<asp:Content ID="contentHolder" ContentPlaceHolderID="ContentPlaceHolder" runat="Server"> 
    <div id="mainContent">

<div id="sidecol">
    <uc1:sideMenuControl ID="SideMenuControl1" runat="server" />

</div>
<div id="content">
    <h1>Upload your company logo here</h1>
<asp:Label ID="Label3" runat="server" Text="Select your Logo File:"></asp:Label>
                <br />
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <br />
                <asp:Label ID="Label1" runat="server"></asp:Label>
                <br />
                <asp:Button ID="Button1" runat="server" Text="Update my Logo" />
                <br />
                <asp:Label ID="Label2" runat="server"></asp:Label>
            </ContentTemplate>
            <Triggers>
                <asp:PostBackTrigger ControlID="Button1" />
            </Triggers>
        </asp:UpdatePanel>
      </div>      
      </div>
 </asp:Content>

这是有效的 VB 脚本:

Imports System.Data
Imports System.Collections.Generic
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Text.RegularExpressions.Regex


Partial Class _Default
    Inherits System.Web.UI.Page

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

        If FileUpload1.FileContent.Length > 0 Then

            

        End If

        If FileUpload1.FileContent.Length > 0 Then
            Label1.Text = ""
            Label2.Text = "Starting upload of: " + FileUpload1.FileName.ToString().Trim()

            SaveToDB(FileUpload1.FileName.ToString().Trim())
            'Dim imageInfo As FileInfo = New FileInfo(FileUpload1.Value.ToString().Trim())
            'Select Case (imageInfo.Extension.ToUpper())
            '    Case ".JPG" : SaveToDB(Me.FileUpload1.Value.Trim())
            '    Case ".JPEG" : SaveToDB(Me.FileUpload1.Value.Trim())
            '    Case ".GIF" : SaveToDB(Me.FileUpload1.Value.Trim())
            '    Case ".BMP" : SaveToDB(Me.FileUpload1.Value.Trim())
            '    Case ".PNG" : SaveToDB(Me.FileUpload1.Value.Trim())
            '    Case Else
            'ClientScript.RegisterClientScriptBlock(Me.GetType(), "alertMsg", "<script>alert('Error: Unknown File Type.');</script>")
            'End Select
        Else
            Label1.Text = "Please choose a file and try again"
            Label2.Text = "" + FileUpload1.FileName.ToString()
        End If

    End Sub

    Private Sub SaveToDB(ByVal name As String)
        Dim objconn As SqlConnection
        objconn = New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
        Dim objCom As SqlCommand
        Try
            Dim size As Integer = FileUpload1.FileContent.Length
            Dim position As Integer = name.LastIndexOf("\")
            name = name.Substring(position + 1)
            Dim contentType As String = FileUpload1.PostedFile.ContentType
            Dim fileData As Byte() = New Byte(size - 1) {}
            FileUpload1.PostedFile.InputStream.Read(fileData, 0, size)
            Label2.Text = fileData.ToString()
            objCom = New SqlCommand("insert into Logos(UserID,Logo) values (@UserID,@Logo)", objconn)
            Dim useridparameter As SqlParameter = New SqlParameter("@UserID", SqlDbType.Int)
            useridparameter.Value = "251"
            objCom.Parameters.Add(useridparameter)
            Dim logoparameter As SqlParameter = New SqlParameter("@Logo", SqlDbType.Image)
            logoparameter.Value = fileData
            objCom.Parameters.Add(logoparameter)
            objconn.Open()
            objCom.ExecuteNonQuery()
            objconn.Close()
            Label2.Text = "Logo uploaded successfully!"
        Catch ex As Exception
            Label1.Text = "" + name
            Label2.Text = "Failed: " + ex.ToString()
        End Try

    End Sub

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        'Form.Enctype() = "multipart/form-data"
    End Sub
End Class