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

时间:2015-01-04 01:21:08

标签: html sql asp.net vb.net image-uploading

我正在尝试编写一个页面来将徽标上传到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'在我的客户端(不是服务器)上,如果我授予每个人对该文件的完全控制权限,则它会成功上传到远程服务器。

我无法让我的用户更改上传文件的权限。

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

带有SQL Server 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

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

2 个答案:

答案 0 :(得分:0)

请尝试以下方法。 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

答案 1 :(得分:0)

非常感谢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