第二次上传文件时会保存

时间:2018-01-10 05:23:39

标签: c# asp.net

<div class="PriceCalculatorForm">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Panel ID="PnlSaveData" runat="server">
                 <div class="form-group">
                     <div class="col-md-1"></div>
                     <label class="control-label col-sm-4">Upload Image</label>
                     <div class="col-sm-4">
                         <asp:FileUpload ID="ImageFileUploader" runat="server" />
                         <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
                     </div>
                     <div class="col-md-2">
                         <asp:Button ID="btnImageUpload" runat="server" Text="Upload Image" OnClick="btnImageUpload_Click" CssClass="btnSearch" />
                     </div>
                     <div class="col-md-1"></div>
                 </div>
             </asp:Panel>           
         </ContentTemplate>
         <Triggers>
             <asp:PostBackTrigger ControlID="btnImageUpload"  />
         </Triggers>
     </asp:UpdatePanel>
</div>

protected void btnImageUpload_Click(object sender, EventArgs e)
{
    if (ImageFileUploader.HasFile)
    {
        string FileExtension = Path.GetExtension(ImageFileUploader.FileName);

        if (FileExtension.ToLower() == ".jpg" || FileExtension.ToLower() == ".jpeg" || FileExtension.ToLower() == ".png" || FileExtension.ToLower() == ".gif")
        {
            string FileName = ImageFileUploader.FileName;

            //Saving the file 
            ImageFileUploader.SaveAs(Server.MapPath("~/Images/" + FileName));
        }
    }
    else
    {
        lblMsg.Text = "Please select file to upload";
        lblMsg.ForeColor = System.Drawing.Color.Red;
    }
}  

问题:

首次上传文件后运行代码后,它会进入代码的其他部分,但是再次上传时相同的文件正常工作,文件保存在指定位置。每次执行都会发生这种情况。我不知道出了什么问题。

请有人能指导我这个吗?

2 个答案:

答案 0 :(得分:0)

每个人都感谢您的支持。最后,我得到了解决方案并最终在this.Page.Form.Enctype = "multipart/form-data"事件下添加了Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    this.Page.Form.Enctype = "multipart/form-data";
}

答案 1 :(得分:0)

如果你喜欢这样的话,可以将你的表格标签更改为:

<form action="" method="post" enctype="multipart/form-data" id="form">
     // your code
</form>