upload.js 11.2 KB
var $ = require('jquery');

$.fn.ajaxfileupload = function (options) {

    return this.each(function () {
        var settings = {
            params: {},
            action: '',
            onStart: function () { },
            onComplete: function (response) { },
            onCancel: function () { },
            validate_extensions: true,
            valid_extensions: ['gif', 'png', 'jpg', 'jpeg'],
            // added by xuhongyun for upload limit
            // 上传大小: 单位kb, 默认限制50mb
            // size="500" spec="1500*1500"
            size_limit: 200 * 1024,

            // 图片规格 width * heith,单位px, 默认不限制
            valid_spec: false,
            width_limit: 0,
            height_limit: 0,
            // end added

            submit_button: null
        };

        var uploading_file = false;

        if (options) {
            $.extend(settings, options);
        }
        var $element = $(this);
        if ($element.data('ajaxUploader-setup') === true) return;

        //支持别的格式上传
        var extend = $element.attr("extend");
        if (extend) {
            settings.valid_extensions = extend.split(',');
        }

        // add by xuhongyun for upload limit
        var size = $element.attr("size");
        if (size) {
            settings.size_limit = parseInt(size);
        }

        var spec = $element.attr("spec");
        if (spec) {
            var array = spec.split('*');
            if (array.length == 2) {
                settings.width_limit = parseInt(array[0]);
                settings.height_limit = parseInt(array[1]);
            }

            if (settings.width_limit != 0 || settings.height_limit != 0) {
                settings.valid_spec = true;
            }
        }
        // end added
    	var bucket = $element.attr("bucket");
    	if(bucket){
      		settings.params.bucket=bucket;
    	}
    	console.log(settings.params);

        $element.change(function () {
            uploading_file = false;
            if (settings.submit_button == null) {
                upload_file();
            }
        });

        if (settings.submit_button == null) { } else {
            settings.submit_button.click(function (e) {
                e.preventDefault();
                if (!uploading_file) {
                    upload_file();
                }
            });
        }

        var upload_file = function () {
            if ($element.val() == '') return settings.onCancel.apply($element, [settings.params]);

            var ext = $element.val().split('.').pop().toLowerCase();
            console.log(settings.validate_extensions);

            // add by xuhongyun for upload limit
            // 校验图片,非图片,直接跳过
            var image_ext = ['gif', 'png', 'jpg', 'jpeg'];
            if ($.inArray(ext, image_ext) > -1) {
                var files = $element[0].files;
                if (files) {
                    $.each(files, function (index, file) {
                        // 加载图片,为了获取图片大小
                        var windowURL = window.URL || window.webkitURL;
                        var dataURL = windowURL.createObjectURL(file);

                        var frame_id = 'preview-' + Math.round(new Date().getTime());
                        $('<img id="' + frame_id + '"  style="display:none" />').appendTo('body').attr("src", dataURL);
                        var img = $('#' + frame_id)[0];

                        // 对文件大小做校验
                        if (file.size / 1024 > settings.size_limit) {
                            // 上传大小超出限制。
                            var message = '只允许上传大小' + settings.size_limit + 'KB以内的文件.';
                            if(files.length > 1) {
                                message += '第' + (index + 1) + '个文件不符合要求!';  // 这里,只有上传多张图片时,才提示不符合要求的图片索引;否则,在像店铺装修存在多个上传组件的情况下,容易造成误解
                            }
                            settings.onComplete.apply($element, [{
                                status: false,
                                message: message
                            }, settings.params]);
                            var _$element = $element.clone();
                            var _$parent = $element.parent();
                            $element.remove();
                            _$parent.append(_$element);
                            _$element.ajaxfileupload(settings);
                            return;
                        }

                        // 对文件尺寸做校验,异步加载
                        img.onload = function () {
                            var width = $(img).width(),
                                height = $(img).height();

                            // 对上传的图片大小进行校验
                            if (settings.valid_spec == true) {
                                var status = true;
                                var message;
                                if (settings.width_limit > 0) {
                                    // 只限制宽度
                                    if (settings.height_limit == 0) {
                                        if (Math.abs(width - settings.width_limit) > 10) {
                                            status = false;
                                            message = '只允许上传宽度为' + settings.width_limit + '的图片.';
                                        }
                                    } else {
                                        if (Math.abs(width - settings.width_limit) > 10 || Math.abs(height - settings.height_limit) > 10) {
                                            status = false;
                                            message = '只允许上传尺寸为' + settings.width_limit + '*' + settings.height_limit + '的图片.';
                                        }
                                    }
                                } else {
                                    // 只限制高度
                                    if (Math.abs(height - settings.height_limit) > 10) {
                                        status = false;
                                        message = '只允许上传高度为' + settings.height_limit + '的图片.';
                                    }
                                }

                                if (status == false) {
                                    // 图片规格超出限制
                                    if(files.length > 1) {
                                        message += '第' + (index + 1) + '个文件不符合要求!';
                                    }
                                    settings.onComplete.apply($element, [{
                                        status: false,
                                        message: message
                                    }, settings.params]);
                                    var _$element = $element.clone();
                                    var _$parent = $element.parent();
                                    $element.remove();
                                    _$parent.append(_$element);
                                    _$element.ajaxfileupload(settings);
                                    return;
                                }
                            }

                            // 校验通过,上传至服务器
                            uploading_file = true;
                            // 记录文件的原始尺寸
                            settings.params.attrs = {
                                width: width,
                                height: height,
                                size: file.size
                            };

                            var ret = settings.onStart.apply($element, [settings.params]);
                            wrapElement($element);
                            if (ret !== false) {
                                $element.parent('form').submit(function (e) {
                                    e.stopPropagation();
                                }).submit();
                            }
                        };
                    });
                }
            } else {
                if (true === settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1) {
                    settings.onComplete.apply($element, [{
                        status: false,
                        message: '文件类型无效.只支持' + settings.valid_extensions.join(',')
                    }, settings.params]);
                    var _$element = $element.clone();
                    var _$parent = $element.parent();
                    $element.remove();
                    _$parent.append(_$element);
                    _$element.ajaxfileupload(settings);
                } else {
                    uploading_file = true;
                    var ret = settings.onStart.apply($element, [settings.params]);
                    wrapElement($element);
                    if (ret !== false) {
                        $element.parent('form').submit(function (e) {
                            e.stopPropagation();
                        }).submit();
                    }
                }
            }
        };
        $element.data('ajaxUploader-setup', true);
        var handleResponse = function (loadedFrame, element) {
            var response, responseStr = $(loadedFrame).contents().text();
            try {
                response = JSON.parse(responseStr);
            } catch (e) {
                response = responseStr;
            }
            element.siblings().remove();
            element.unwrap();

            uploading_file = false;

            settings.onComplete.apply(element, [response, settings.params]);
            var _$element = $element.clone();
            var _$parent = $element.parent();
            $element.remove();
            _$parent.append(_$element);
            _$element.ajaxfileupload(settings);
        };
        var wrapElement = function (element) {
            var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
            $('body').after('<iframe width="0" height="0" style="display:none;" name="' + frame_id + '" id="' + frame_id + '"/>');
            $('#' + frame_id).get(0).onload = function () {
                handleResponse(this, element);
            };
            element.wrap(function () {
                return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="' + frame_id + '" />'
            })
                .before(function () {
                    var key, html = '';
                    for (key in settings.params) {
                        var paramVal = settings.params[key];
                        if (typeof paramVal === 'function') {
                            paramVal = paramVal();
                        }
                        html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
                    }
                    html += '<input type="hidden" name="filename" value="' + $element.attr("name") + '" />'
                    return html;
                });
        }

    });
}


module.exports = $;