How to restrict file type in FileUpload control

后端 未结 8 2048
清歌不尽
清歌不尽 2020-11-30 09:29

Is it possible to allow the fileupload control to show only images?

When we click the Browse button it should show only images.

相关标签:
8条回答
  • 2020-11-30 10:06

    I found no direct solution for this problem.

    This is my workaround using the RegularExpressionValidator:

    <asp:FileUpload ID="fuImportImage" runat="server" />
    <asp:RegularExpressionValidator ID="regexValidator" runat="server"
         ControlToValidate="fuImportImage"
         ErrorMessage="Only JPEG images are allowed" 
         ValidationExpression="(.*\.([Jj][Pp][Gg])|.*\.([Jj][Pp][Ee][Gg])$)">
    </asp:RegularExpressionValidator>
    
    0 讨论(0)
  • 2020-11-30 10:10

    No, in web you can't from client side, evidently from server side you can do amazing things. For this kind of thing, programmers normally use Activex, flash or the like.

    0 讨论(0)
  • 2020-11-30 10:15

    You cannot strictly restrict the file type, but if the browser supports it you can cause it to initially show just a certain type of file:

    <form method="post" action="blahblah.blah">
      <input type="file" name="image" id="image" accept="image/png, image/jpeg" />
    </form>
    
    0 讨论(0)
  • 2020-11-30 10:21
    //VALIDATE FILE EXTENTION
    var _validFileFlag;
    function fValidFileExt(vfilePath){
      var vFileName=vfilePath.split('\\').pop();
      var vFileExt=vfileName.split('.').pop();
      if(vFileExt.toUpperCase()=="JPEG" || vFileExt.toUpperCase()=="JPG"){
         _validFileFlag = true;
      } 
      _validFileFlag = false;
    } 
    
    <asp:FileUpload ID="FileUpload1" onchange="fValidFileExt(this.value);" runat="server"  />
    

    Check '_validFileFlag' while saving data/upload..

    0 讨论(0)
  • 2020-11-30 10:21

    Use accept attribute to show only images in file browser like below -

    <asp:FileUpload ID="FileUploadFileType" runat="server" CssClass="form-control" accept=".png,.jpg,.jpeg,.gif" />
    

    with asp.nets RegularExpressionValidator to validate selected file type with validation message.

    <asp:RegularExpressionValidator ID="RegExValFileUploadFileType" runat="server"
                            ControlToValidate="FileUploadFileType"
                            ErrorMessage="Only .jpg,.png,.jpeg,.gif Files are allowed" Font-Bold="True"
                            Font-Size="Medium"
                            ValidationExpression="(.*?)\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)$"></asp:RegularExpressionValidator>
    
    0 讨论(0)
  • 2020-11-30 10:23

    In 2015, web browsers support the input accept attribute, so you can do this:

    <asp:FileUpload ID="fileUploader" runat="server" accept=".png,.jpg,.jpeg,.gif" />
    

    Keep in mind Visual Studio may show you a message about this as an invalid attribute of the FileUpload ASP tool, however.

    0 讨论(0)
提交回复
热议问题