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

本文关键字:文件 类型 验证 | 更新日期: 2023-09-27 18:18:23

我写了下面几行代码

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

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

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

您的验证表达式应该像这样

([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 post validate -of-file-extension-before- uploadingfile