0

I am trying to implement a file upload in my web form, It tried this.

<asp:Label ID="lbl1" runat="server" Text="Press browse!"></asp:Label>
<br />
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" />
Protected Sub btnUpload_Click(sender As Object, e As EventArgs) Handles btnUpload.Click
    If FileUpload1.HasFile Then
        Try
            FileUpload1.SaveAs("Images\" & FileUpload1.FileName)
            lbl1.Text = "File name: " & _
                FileUpload1.PostedFile.FileName & "<br>" & _
                "File Size: " & _
                FileUpload1.PostedFile.ContentLength & "<br>" & _
                "Content type: " & _
                FileUpload1.PostedFile.ContentType
        Catch ex As Exception
            lbl1.Text = "ERROR: " & ex.Message.ToString()
        End Try
    Else
        lbl1.Text = "You have not specified a file."
    End If
End Sub

But gives me an error saying file path is not rooted. I am running this locally at the moment and when I replace the file path with this 'C:Users/Me/Documents/MYPROJECTNAME/MYPROJECTNAME/Images' it works fine. This will go online so what am I meant to write as the file path?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
thephysicsguy
  • 403
  • 1
  • 4
  • 15

1 Answers1

1

You need to use Server.MapPath to resolve the path of your Images folder relative to your project physical path (so it works for both locally and when you deploy your app).

FileUpload1.SaveAs(Server.MapPath("~\Images\") & FileUpload1.FileName)

~ returns the path of the root of your app.

Here is a great explanation on Server.MapPath.

Community
  • 1
  • 1
singularhum
  • 5,072
  • 2
  • 24
  • 32