简体   繁体   中英

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

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. +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. you also cannot add the NetworkService account to local Administrators (I know, I know - bad security - but I'm just troubleshooting here).

IIS 6 with SQL server 2008 R2 is hosting the site.

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:

 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.

Change asp control to:

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

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:

 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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