使用jQuery验证文件类型并显示图像预览 [英] Validating filetype and display image preview using jQuery

查看:88
本文介绍了使用jQuery验证文件类型并显示图像预览的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个脚本可以很好地运行,一个脚本验证所选文件为jpeg,然后输出警报,如下所示:

I have two scripts that work fine on their own, one validates that the file selected is a jpeg and then outputs a alert, which is given below:

(function($) {
    $.fn.checkFileType = function(options) {
    var defaults = {
        allowedExtensions: [],
        success: function() {},
        error: function() {}
    };
    options = $.extend(defaults, options);

    return this.each(function() {

        $(this).on('change', function() {
            var value = $(this).val(),
                file = value.toLowerCase(),
                extension = file.substring(file.lastIndexOf('.') + 1);

            if ($.inArray(extension, options.allowedExtensions) == -1) {
                options.error();
                $(this).focus();
            } else {
                options.success();

            }

        });

    });
};

})(jQuery);

$(function() {
$('#image').checkFileType({
    allowedExtensions: ['jpg', 'jpeg'],
    success: function() {
        alert('success')
    },
    error: function() {
        alert('Error');

    }
});

});

另一个显示在<img>元素内的所选图像的预览

The other one displays a preview of a selected image inside an <img> element

function readURL(input) {
        if (input.files && input.files[0]) {  

            var reader = new FileReader();

            reader.onload = function (e) {

                $('#productImg').show();

                $('#productImg')
                    .attr('src', e.target.result)

            };

            reader.readAsDataURL(input.files[0]);
        }
    } 

我正在调用上述函数,如下所示:

I'm calling the above function as follows:

<input type="file" name="image" class="browse" id="image" onchange="readURL(this);" />

我想做的是结合两个脚本,以便如果图像不是jpeg,它会像第一个脚本一样警告错误,然后,如果图像是jpeg,它将像第二个脚本一样显示预览脚本.

What I want to do is combine the two scripts so that if the image is not a jpeg it alerts the error like in the first script and then if the image is a jpeg it displays the preview like the second script.

推荐答案

正如我在评论中提到的,您可以简单地将第二个函数指定为第一个函数的成功回调,并在第二个函数中显示警报,或调用第二个警报后的功能(由于您要在第二个功能中对预览元素进行硬编码,因此看起来足以满足当前要求.)

As i mentioned in comments, you can simply specify the second function as the success callback of first function, and show the alert in second function, or call the second function after the alert (Since you're hardcoding the preview element in second function, it looks like that's enough for the current requirement.)

如果您真的想将其概括,则可以尝试以下

If you really want to generalize it, you can try something like below

$.fn.checkFileType = function (options) {
var defaults = {
    allowedExtensions: [],
    preview: "",
    success: function () {},
    error: function () {}
};
options = $.extend(defaults, options);
$previews = $(options.preview);
return this.each(function (i) {

    $(this).on('change', function () {
        var value = $(this).val(),
            file = value.toLowerCase(),
            extension = file.substring(file.lastIndexOf('.') + 1),
            $preview = $previews.eq(i);

        if ($.inArray(extension, options.allowedExtensions) == -1) {
            options.error();
            $(this).focus();
        } else {
            if (this.files && this.files[0] && $preview) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $preview.show().attr('src', e.target.result);
                    options.success();
                };

                reader.readAsDataURL(this.files[0]);
            } else {
                options.error();
            }

        }

    });

  });
};

您可以按以下方式使用它:

You can use it as follows:

$('#image').checkFileType({
  allowedExtensions: ['jpg', 'jpeg',"gif"],
  preview: ".preview",
  success: function () {
    alert('success')
  },
  error: function () {
    alert('Error');
  }
});

preview选项中指定的jQuery选择器匹配的元素集合中,图像将被设置为<input>元素索引处的src.

The image will be set as the src of element at the index of your <input> among the set of elements matched by the jQuery selector specified in preview option.

这篇关于使用jQuery验证文件类型并显示图像预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆