使用AsyncFileUpload控件上载文件并存储它

本文关键字:存储 文件 上载 AsyncFileUpload 控件 使用 | 更新日期: 2023-09-27 18:03:46

我正在做一个项目:

Front end - Visual Studio 2010
Technology : C#
Back end - Sql Server 2005

我正在尝试使用AsyncFileUpload控件上载文件,并将其存储到"~/Image/"文件夹中。

脚本:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" 
            onuploadedcomplete="AsyncFileUpload1_UploadedComplete"/>
    </ContentTemplate>

代码背后:

protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
    if (AsyncFileUpload1.HasFile)
    {
        AsyncFileUpload1.SaveAs("~/Image/" + AsyncFileUpload1.FileName);
        Label2.Text = "Recieved " + AsyncFileUpload1.FileName + " Content Type" + AsyncFileUpload1.PostedFile.ContentType;
    }
}

但每次它显示的运行时错误调用:

The SaveAs method is configured to require a rooted path, and the path '~'Image'Filename.jpg' is not rooted.

我可以知道这个错误和解决方法吗。

提前感谢

Nikhil

使用AsyncFileUpload控件上载文件并存储它

我发现了:

table width="100%" style="font: 8pt verdana">
                <tr width="100%">
                <td width="40%">
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                    <asp:HiddenField ID="HiddenField1" runat="server" />
                </td>
                <td width="40%"><asp:Label ID="lblPicStatus" runat="server"></asp:Label></td>
                <td>
                <asp:Button ID="Button2" runat="server" Text="Upload" BackColor="White" 
                        BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px" 
                        onclick="Button2_Click"/></td>
                </tr>
</table>

代码隐藏,

protected void Button2_Click(object sender, EventArgs e)
{
    try
    {
        con.Open();
        if (FileUpload1.HasFile)
        {
            String fileExt = Path.GetExtension(FileUpload1.FileName);
            if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".jpeg" || fileExt == ".png")
            {
                String path = "~/Image/" + FileUpload1.FileName;
                cmd.CommandText = "update " + HttpContext.Current.User.Identity.Name + " set image = '" + path + "'";
                cmd.Connection = con;
                cmd.ExecuteNonQuery();
                FileUpload1.SaveAs(Server.MapPath("~/Image/") + FileUpload1.FileName);
                Response.Redirect(Request.RawUrl);
            }
            else
            {
                lblPicStatus.Text = "File to be uploaded is not an image";
            }
            con.Close();
        }
    }
    catch (Exception a)
    {
        Response.Write(a.Message);
    }
}
 String path = "~/Image/" + FileUpload1.FileName;

应该是这样的:

 String path = Server.MapPath("~/Image/") + FileUpload1.FileName;