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

huangapple go评论76阅读模式
英文:

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

问题

Page.IsValid返回true,并且它检查文件的扩展名和大小,每一步的调试都显示验证没有问题。但是,单击保存按钮后,即使自定义验证器返回true,hasFile也返回false。请帮忙!

我已经包含了所有的建议:

在Page_Load方法中添加了postbacktrigger:

protected void Page_Load(object sender, EventArgs e)
{
    Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
<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;
    }
}
英文:

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(&quot;enctype&quot;, &quot;multipart/form-data&quot;);

added postbacktrigger:

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

</asp:UpdatePanel>

codebehind:

 protected void btnSavePub_Click(object sender, EventArgs e)
{            
context = PaymentController.GetContext();
paymentCategory = context.Categories.Find(cat =&gt; 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 ?? &quot;Ошибка при сохранении изображений&quot;);
return;
}
}
}              
}
if (!string.IsNullOrWhiteSpace(paymentCategory.WebIcon) &amp;&amp; !string.IsNullOrWhiteSpace(paymentCategory.AndroidIcon) &amp;&amp; !string.IsNullOrWhiteSpace(paymentCategory.IosIcon) &amp;&amp; ddlTitles.SelectedItem.Text != &quot;Не выбрано&quot;)
{
PaymentController.SaveIcon(paymentCategory);
lbResult.Text = &quot;Данные успешно сохранены&quot;;
lbResult.CssClass = &quot;text-success&quot;;
lbResult.Visible = true;
}            
else
{
lbResult.Text = &quot;Ошибка валидностью файлов&quot;;
lbResult.CssClass = &quot;text-danger&quot;;
lbResult.Visible = true;
}

答案1

得分: 1

标准的上传控件在更新面板内无法正常工作。

该控件需要正确且适当的完整页面后台提交。如果您将文件上传控件放置在更新面板内,那么当然您将不会得到标准的页面后台提交,因此文件上传控件将始终显示 "没有文件"。

解决此问题的方法是采用不使用或依赖页面后台提交的 Ajax 文件上传器。

由于这些控件不需要(也不使用)后台提交,所以它们可以在更新面板内正常工作,但另一方面,由于您不需要后台提交,因此在大多数情况下,您也不需要后台提交。

这些 Ajax 上传工具的其他优点是什么?

它们将文件分成块进行上传。这意味着在大多数情况下,您会看到一个很好的进度条。由于使用 "块",文件大小的上传是无限制的。

此外,对于大文件,用户不会遇到浏览器冻结的情况,似乎什么都没有发生。

更重要的是,这些文件上传工具对服务器的压力较小,因为不需要进行大型后台提交。

甚至更好的是,大多数此类上传工具在上传过程中还提供了一个取消按钮。

在今天,以及这些天?

客户期望获得良好和出色的上传体验。有许多选择,而且许多是免费的。

我一直在使用来自 Ajax 工具包的 AjaxFileUploader。现在,仅为了上传工具采用整个 Ajax 工具包可能有点过于庞大,但另一方面,也许您已经在使用 Ajax 工具包。它是免费的、开源的,现在由 DevExpress 的伟大人员维护。

您可以在这里找到它:

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

因此,在操作上,它看起来像这样:

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

除了上述内容,这些 Ajax 上传工具中的大多数还具有拖放文件的热点,或者您可以点击选择以使用标准的文件浏览对话框。

所以,如今?选择一个好的文件上传系统,学会使用它,您将来可以多年使用该系统。几乎没有理由尝试加载自己的上传工具。

另一种选择(我没有使用过的选择)是 FilePond。

https://pqina.nl/filepond/

还有其他选择。

如果您不需要像上面那样 "花里胡哨" 的文件上传工具,那么 Ajax 工具包还有一个 AsyncFileUpload 控件(同样不需要后台提交)。

因此,标准的HTML文件上传控件在放置在更新面板内时无法工作,因为该控件需要进行完整页面后台提交。

英文:

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:

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

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.

答案2

得分: 0

我发现问题不在于回发和上传本身,而是在我检查从输入流中通过XmlReader读取的.svg文件的大小的其他功能中。因此,在执行完输入流后,它被关闭。

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;

因此,由于InputStream已关闭,hasFile当然会返回空值。

英文:

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(&quot;width&quot;);
int w = int.Parse(xmlReader.Value);
xmlReader.MoveToNextAttribute();
int h = int.Parse(xmlReader.Value);
if (w != 32 &amp;&amp; h != 32)
{
return false;
}                    
}
bool hasfile = fileUpload.HasFile;

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

huangapple
  • 本文由 发表于 2023年6月26日 17:25:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76555342.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定