Search code examples
c#asp.netpostbackascx

FileUpload HasFile is false after the CustomValidator and even with the PostBackTrigger


Page.IsValid is returning true and its checking for the file's extensions and size, every step debugging showed there's no problem with validating. But hasFile returning false after clicking the save button even though custom validator returned true. Please help!

i have included all suggestions:

protected void Page_Load(object sender, EventArgs e)
    {
        Page.Form.Attributes.Add("enctype", "multipart/form-data");

added postbacktrigger:

<asp:UpdatePanel runat="server">
<ContentTemplate>      
                    <div class="col-lg-4">
                        <asp:FileUpload runat="server" CssClass="form-control" accept="application/pdf" ID="fupIos" ViewStateMode="Enabled" />
                        <asp:CustomValidator ID="fupIosValidator" runat="server" ForeColor="Red"
                            ErrorMessage="Неверные данные"
                            ControlToValidate="fupIos"
                            OnServerValidate="fupIos_validate" ValidateEmptyText="true">
                        </asp:CustomValidator>
                    </div>
                    <div class="col-lg-4">
                        <asp:FileUpload runat="server" CssClass="form-control androidLoader" ClientIDMode="Static" accept="image/svg+xml" ID="fupAndriod" onchange="preview('.imgAndriod', '.androidLoader')" ViewStateMode="Enabled" />
                        <asp:CustomValidator ID="fupAndriodValidator" runat="server" ForeColor="Red"
                            ErrorMessage="Неверные данные"
                            ControlToValidate="fupAndriod"
                            OnServerValidate="fupAndriod_validate" ValidateEmptyText="true">
                        </asp:CustomValidator>
                    </div>
                    <div class="col-lg-4">
                        <asp:FileUpload runat="server" CssClass="form-control webLoader" ClientIDMode="Static" accept="image/png" ID="fupWeb" onchange="preview('.imgWeb', '.webLoader')" ViewStateMode="Enabled" />
                        <asp:CustomValidator ID="fupWebValidator" runat="server" ForeColor="Red"
                            ErrorMessage="Неверные данные"
                            ControlToValidate="fupWeb"
                            OnServerValidate="fupWeb_validate" ValidateEmptyText="true">
                        </asp:CustomValidator>
                    </div>
                
</ContentTemplate>
<Triggers>
    <asp:PostBackTrigger ControlID="btnSavePub" />
    <asp:PostBackTrigger ControlID="lbtnIos" />
</Triggers>

</asp:UpdatePanel>

codebehind:

 protected void btnSavePub_Click(object sender, EventArgs e)
    {            
        context = PaymentController.GetContext();
        paymentCategory = context.Categories.Find(cat => cat.Id == CategoryId);
        string iconId = ddlTitles.SelectedValue.ToString();
        SrvUploaderData srvUploaderData = new SrvUploaderData();
        SrvUploaderResult srvUploaderResult = new SrvUploaderResult();
        SrvUploaderCategory category;

        if (Page.IsValid)
        {               
            //media inputs
            foreach (var media in new[] { fupIos, fupAndriod, fupWeb })
            {
                if (media.HasFile)
                {
                    category = new SrvUploaderCategory()
                    {
                        ImgId = !string.IsNullOrWhiteSpace(iconId) ? iconId : null,
                        Img = media.FileName,
                    };
                    FrameworkController.UploadCategoryIconData(category, media.FileBytes, out srvUploaderData, out srvUploaderResult);
                    if (srvUploaderResult.Success)
                    {
                        SetIcon(paymentCategory, media, srvUploaderData.Link);
                    }
                    else
                    {
                        ShowError(srvUploaderResult?.Message ?? "Ошибка при сохранении изображений");
                        return;
                    }
                }
            }              
        }
        if (!string.IsNullOrWhiteSpace(paymentCategory.WebIcon) && !string.IsNullOrWhiteSpace(paymentCategory.AndroidIcon) && !string.IsNullOrWhiteSpace(paymentCategory.IosIcon) && ddlTitles.SelectedItem.Text != "Не выбрано")
        {
            PaymentController.SaveIcon(paymentCategory);
            lbResult.Text = "Данные успешно сохранены";
            lbResult.CssClass = "text-success";
            lbResult.Visible = true;
        }            
        else
        {
            lbResult.Text = "Ошибка валидностью файлов";
            lbResult.CssClass = "text-danger";
            lbResult.Visible = true;
        }

Solution

  • I found the issue was not on postback and upload itself, it is in other function where I check for the size of the .svg file by reading through XmlReader from input stream. So after it executes the input stream is closed.

                using (var xmlReader = new XmlTextReader(fileUpload.PostedFile.InputStream))
                {
                    xmlReader.MoveToContent();
                    xmlReader.MoveToAttribute("width");
                    int w = int.Parse(xmlReader.Value);
                    xmlReader.MoveToNextAttribute();
                    int h = int.Parse(xmlReader.Value);
                    if (w != 32 && h != 32)
                    {
                        return false;
                    }                    
                }
                bool hasfile = fileUpload.HasFile;
    

    So after hasFile is ofcourse returning empty as the InputStream is closed.