文件上传时的文件类型验证

时间:2015-10-20 07:45:24

标签: c# asp.net validation c#-4.0 file-upload

我写了下面的代码行

<section class="col col-md-6">
  <label for="file" class="input input-file">
    Upload Image/Video
    <label for="file" class="input input-file">
      <div class="button">
        <asp:FileUpload ID="UploadSlider1" runat="server" onchange="this.parentNode.nextSibling.value = this.value" />Browse</div>
      <input type="text" readonly />
    </label>
    <asp:HiddenField ID="hdnUploadSlider1" runat="server" />
    <asp:CustomValidator ID="CustomValidator1" ControlToValidate="UploadSlider1" OnServerValidate="ValidateFileSize1" runat="server" />
    <asp:RegularExpressionValidator ID="UploadSlider1regularexpression" runat="server" ControlToValidate="UploadSlider1" Display="Dynamic" ErrorMessage="Only Images are allowed" SetFocusOnError="true" CssClass="state-error" ValidationExpression="^.*\.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(g|G))$"></asp:RegularExpressionValidator>
</section>
<section class="col col-md-6">
  <label for="file" class="input input-file">
    Upload Image/Video
    <label for="file" class="input input-file">
      <div class="button">
        <asp:FileUpload ID="UploadSlider1" runat="server" onchange="this.parentNode.nextSibling.value = this.value" />Browse</div>
      <input type="text" readonly />
    </label>
    <asp:HiddenField ID="hdnUploadSlider1" runat="server" />
    <asp:CustomValidator ID="CustomValidator1" ControlToValidate="UploadSlider1" OnServerValidate="ValidateFileSize1" runat="server" />
    <asp:RegularExpressionValidator ID="UploadSlider1regularexpression" runat="server" ControlToValidate="UploadSlider1" Display="Dynamic" ErrorMessage="Only Images are allowed" SetFocusOnError="true" CssClass="state-error" ValidationExpression="^.*\.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(g|G))$"></asp:RegularExpressionValidator>
</section>

现在我希望该用户只能上传图片和视频文件。请帮我如何在一个正则表达式中对这两种类型进行验证。

1 个答案:

答案 0 :(得分:0)

你的验证表达应该是这样的

([a-zA-Z0-9\s_\\.\-:])+(.png|.PNG|.jpg|.JPG|.gif|.mp4|.mpg|.3gp)$

根据需要添加尽可能多的变体|作为分隔符

<asp:RegularExpressionValidator Display="Dynamic" ValidationExpression="([a-zA-Z0-9\s_\\.\-:])+(.png|.PNG|.jpg|.gif|.mp4|.mpg|.3gp)$" ControlToValidate="UploadSlider1" runat="server" ForeColor="Red" ErrorMessage="Please select a valid Image or Video File file." ID="RegularExpressionValidator1" />

JavaScript版本:
如果您觉得使用JavaScript很容易,可以按照此SO帖子validation-of-file-extension-before-uploading-file

进行操作