FileUpload Object Rooted path错误

时间:2014-04-06 00:21:07

标签: asp.net vb.net

我正在尝试在我的网络表单中实现文件上传,它尝试了这个。

<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

但是给我一个错误,说文件路径没有root。我正在本地运行这个,当我用'C:Users / Me / Documents / MYPROJECTNAME / MYPROJECTNAME / Images'替换文件路径时,它运行正常。这将上线所以我打算写什么作为文件路径?

1 个答案:

答案 0 :(得分:1)

您需要使用Server.MapPath来解析Images文件夹相对于项目物理路径的路径(因此它适用于本地和部署应用时)。

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

~会返回应用根目录的路径。

Here是Server.MapPath的一个很好的解释。