jQuery - INPUT type=File , Image FileType Validation options?

后端 未结 6 1862
误落风尘
误落风尘 2020-12-29 09:08

I have the following:


On the server I check to make sure it\

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 09:23

    How can we to check, that user selects image file?

    • By file extension validation
      It's work as expected, text file with .png extension pass here
    • input[type=file][accept=image/*] It initially hides non-image files from user. But this filter works by extensions too. And user still can manually enter any existing file name.
    • We can check mime type of result dataUrl, it starts with data:mimetype;base64,.... So, we need image/* mimetype.

      var file = $('#uploadfile');
      file.on('change', function (e) {
          var reader = new FileReader();
      
          reader.onload = function() {
              var data = reader.result;
              if (data.match(/^data:image\//)) {
                  $('#thumbnail').attr('src', data);
              } else {
                  console.error('Not an image');
              }
          };
      
          reader.readAsDataURL(file.prop('files')[0]);
      });
      

提交回复
热议问题