This is my `.aspx` for `FileuUpload` ..
<asp:FileUpload ID="FileUpload1" runat="server" class="multi form-control" />
<asp:CustomValidator ID="ValidatorUpload" runat="server" ErrorMessage="File Upload Tidak boleh kosong" ControlToValidate="FileUpload1" Display="Dynamic" OnServerValidate="ValidatorUpload_ServerValidate"></asp:CustomValidator>
这是我的.aspx.cs
(代码背后)。
protected void ValidatorUpload_ServerValidate(object source, ServerValidateEventArgs args)
{
FileUpload Upload = (FileUpload)FormView1.FindControl("FileUpload1");
HttpPostedFile hpf = Upload.PostedFile;
if (((CustomControls_DdlLocation)FormView1.Controls[0].FindControl("ddl_location1")).SelectedText.ToLower().Trim() == "kelanis")
{
if (hpf.FileName == null)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
}
如果FileUpload
为Empty
但我的代码无效,我想显示消息。
需要一个解决方案。
答案 0 :(得分:1)
我用过这个。工作实际上
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:requiredfieldvalidator errormessage="Required" controltovalidate="FileUpload1"
runat="server" display="Dynamic" forecolor="Red" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="([a-zA-Z0-9\s_\\.\-:])+(.doc|.docx|.pdf)$"
ControlToValidate="FileUpload1" runat="server" ForeColor="Red" ErrorMessage="Please select a valid Word or PDF File file."
Display="Dynamic" />
<br />
<asp:button text="Submit" runat="server" />
对于图像,您可以使用以下正则表达式验证器
([a-zA-Z0-9\s_\\.\-:])+(.png|.jpg|.gif)$
由于
答案 1 :(得分:1)
你应该试试这个
if (hpf.HasFile == false)
{
if ( hpf.FileName != "")
{
args.IsValid = false;
}
}
答案 2 :(得分:1)
请使用试试这个
protected void checkfilesize(object source, ServerValidateEventArgs args)
{
string data = args.Value;
args.IsValid = false;
double filesize = FileUpload1.FileContent.Length;
if (filesize > 5000)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
答案 3 :(得分:1)
你可以尝试这个解决方案
<asp:RequiredFieldValidator ID="rfvDocument" runat="server" ErrorMessage="Upload your file!" ValidationGroup="NewDocument" ControlToValidate="fuDocument" Display="Dynamic"></asp:RequiredFieldValidator>
<asp:FileUpload ID="fuDocument" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload File" ValidationGroup="NewDocument" />
&#13;
并且在服务器代码中记得放入将开始保存文件的按钮代码:
Me.Validate("NewDocument");
If (Me.IsValid) {
//your code
}