skip to Main Content

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;
        }

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. A standard up-load control does NOT work inside of a update panel.

    That control requires a correct and proper FULL page post-back. If you place the fileupload control inside of a update panel, then of course you don’t get a standard page post-back, and as a result, the file upload control will always show "no file".

    The solution to this is to adopt a ajax file up-loader that does not use nor rely on a page post-back.

    Since such controls don’t require (nor use) a post-back, then they do work inside of a update panel, but then again, since you don’t have nor require a post-back, then in most cases you don’t need nor want a post-back anyway.

    The other advantages of these ajax up-loaders?

    They send up the file in chunks. This means in most cases you have a nice progress bar. And due to using "chunks", then file size up-load is un-limited.

    Furthermore, with a large file, then the user does not experiance a browser freeze up in which it seems nothing is occuring.

    And even better, these file up-loaders tend to put less stress on the sever, since some BIG HUGE post-back does not have to occur.

    And even better, is most such up-loaders also provide a nice cancel button duruing up-load.

    At the end of the day, and these days?

    Customers expect a good and great up-load experiance. There are MANY choices, and many are free.

    I been using the AjaxFileUploader from the ajax tool kit. Now adopting the WHOLE ajaxtoolkit for JUST the up-loader is a bit of a large library to adopt, but then again, perhaps you already using the aj toolkit. It is free, and open source, and is now maintained by the great folks from DevExpress.

    You can find it here:

    https://www.devexpress.com/Products/AJAX-Control-Toolkit/

    So, in operation, it looks like this:

    enter image description here

    In addition to above, most of these ajax up-loaders also have a hot spot to drag and drop files, or you can hit select for the standard file browse dialog.

    So, these days? Grab a good file up-load system, lean to use it, and you use that system for years to come. There is LITTLE reason to try and load your own up-loader.

    Another choice (one I not used), is file pond.

    https://pqina.nl/filepond/

    And there are others.

    and if you don’t need a "fancy pants" file up-loader like above, the aj toolkit also has a AsyncFileUpLoad control (and again does not require a post-back).

    So, the standard HTML file upload control simple does not work when placed inside of a update panel due to that control requiring a full page post-back.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search