简体   繁体   English

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

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

I'm attempting to write a page to upload a logo onto a SQL database. 我正在尝试编写一个页面以将徽标上载到SQL数据库。 However, I keep getting access denied errors. 但是,我不断收到访问被拒绝的错误。 When I run the procedure, the following exception is thrown: 当我运行该过程时,将引发以下异常:

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

The file: 'C:\\Users\\ANDY\\Pictures\\Logo.PNG' is on my client (not the server) and if I grant everyone full control permissions to the file, then it uploads to the remote server successfully. 文件:“ C:\\ Users \\ ANDY \\ Pictures \\ Logo.PNG”位于我的客户端(而不是服务器)上,如果我授予所有人对该文件的完全控制权限,则该文件将成功上传到远程服务器。

I cant ask my users to change their permissions to upload files. 我不能要求我的用户更改其上传文件的权限。

during my testing I have tried it on 2 computers: +My development computer: -in debug mode in visual studio, it works great -on the same computer, if I load it into IIS it throws an the exception above requiring permissions to be granted to the local file or folder that I am trying to upload. 在测试期间,我已经在2台计算机上进行了尝试:+我的开发计算机:-在Visual Studio中以调试模式运行,效果很好-在同一台计算机上,如果我将其加载到IIS中,则会引发上述异常,要求授予权限到我尝试上传的本地文件或文件夹。 +My Production Server: -The same files uploaded to the production server produce a slightly different error. +我的生产服务器:-上载到生产服务器的相同文件会产生稍微不同的错误。 This time it wants permissions to modify this path on the server: c:\\Windows\\System32\\inetsrv I thought I'd try granting access to this folder to the NetworkService account, however, it appears that this is a protected folder and you cannot modify permissions to folders under System32. 这次,它需要权限来修改服务器上的该路径:c:\\ Windows \\ System32 \\ inetsrv我以为我会尝试将对该文件夹的访问权限授予NetworkService帐户,但是,看来这是一个受保护的文件夹,您不能修改对System32下文件夹的权限。 you also cannot add the NetworkService account to local Administrators (I know, I know - bad security - but I'm just troubleshooting here). 您也不能将NetworkService帐户添加到本地管理员(我知道,我知道-安全性较差-但我只是在这里进行故障排除)。

IIS 6 with SQL server 2008 R2 is hosting the site. 带有SQL Server 2008 R2的IIS 6托管该站点。

Web page code is as follows: 网页代码如下:

 <%@ 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 codefile is as follows: 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 

I'm puzzled as to why the system needs write access to the file that it is reading for upload. 我对系统为什么需要对正在读取的文件进行写访问权限感到困惑。 maybe you guys and gals can help me out? 也许你们和女友可以帮我吗?

Try this below. 请在下面尝试。 fileData is what you will pass to you sql. fileData是您将传递给sql的内容。

Change asp control to: 将ASP控件更改为:

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

Then use: 然后使用:

  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

Many thanks to RickJames who helped me out with this conundrum. 非常感谢RickJames帮助我解决了这个难题。 He's awesome! 他很棒! here is the final working code for the file upload routine that tested out ok on all my machines. 这是文件上传例程的最终工作代码,该代码在我所有的机器上都经过了正常测试。 I guess it was the full path that was stopping the process from working correctly and the FileUpload control handles that for you: 我想这是阻止该进程正常运行的完整路径,而FileUpload控件可以为您处理:

Web Page: 网页:

 <%@ 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> 

and here is the working VB script: 这是有效的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 

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

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