使用jQuery裁剪图像之前进行文件类型验证

时间:2018-11-14 11:45:25

标签: javascript jquery

我有使用jropropie插件的裁剪图像代码,并使用bootstrap modal上传。就我而言,我与FileReader

$(document).ready(function(){

    $image_crop = $('#image_demo').croppie({
        enableExif: true,
        viewport: {
            width:200,
            height:300,
            type:'square' //circle
        },
        boundary:{
            width:300,
            height:300
        }
    });
    var fileTypes = ['jpg', 'jpeg', 'png'];
    $('#upload_image').on('change', function(){
        var reader = new FileReader();
        reader.onload = function (event) {
            $image_crop.croppie('bind', {
                url: event.target.result
            }).then(function(){
                console.log('jQuery bind complete');
            });
        }
        reader.readAsDataURL(this.files[0]);
        $('#uploadimageModal').modal('show');
    });

    $('.crop_image').click(function(event){
        $image_crop.croppie('result', {
            type: 'canvas',
            size: 'viewport'
        }).then(function(response){
            $.ajax({
                url:"../account/edit/profileimage",
                type: "POST",
                //dataType:"json",
                data:{"image": response},
                success:function(data)
                {
                    /*
                    if(response.status === 'error'){
                        $('#uploadimageModal').animate({ scrollTop: $('#uploaderror').offset().top }, 500);
                        $('#uploaderror').html(response.message);
                    }
                    else {
                    */
                        $('#uploadimageModal').modal('hide');
                        $('#uploaded_image').html(data);
                     /*
                    }
                    */
                }
            });
        })
    });

});

现在,我需要检查文件类型验证并在加载模式框之前显示警报。我如何显示警报消息?!

1 个答案:

答案 0 :(得分:1)

看看下面的代码。希望对您有帮助

var fileTypes = ['jpg', 'jpeg', 'png'];
$('#upload_image').on('change', function() {
  var reader = new FileReader();
  var file = this.files[0]; // Get your file here
  var fileExt = file.type.split('/')[1]; // Get the file extension

  if (fileTypes.indexOf(fileExt) !== -1) {
    reader.onload = function(event) {
      $image_crop.croppie('bind', {
        url: event.target.result
      }).then(function() {
        console.log('jQuery bind complete');
      });
    }
    reader.readAsDataURL(file);
    $('#uploadimageModal').modal('show');
  } else {
    alert('File not supported');
  }
});