upload.js 1.66 KB
var $ = require('yoho-jquery'),
    handlebars = require('yoho-handlebars');

var tpl = '<div style="width: 0px; height: 0px; overflow: hidden;">' +
        '<iframe id="yoho-upload-result" name="ajaxUpload" style="display:none"></iframe>' +
        '<form id="yoho-upload" method="post" enctype="multipart/form-data" ' +
        'action="/common/uploadImg" target="ajaxUpload">' +
            '<input type="file" name="filename" class="file-name" />' +
            '<input type="hidden" name="bucket" value="evidenceImages" />' +
        '</form>' +
    '</div>';

var uploadFn = handlebars.compile(tpl || '');

var $result,
    $upload,
    $filename;

var uping;

var num,
    inter,
    callback;

$('body').append(uploadFn({}));

$result = $('#yoho-upload-result');
$upload = $('#yoho-upload');
$filename = $upload.find('.file-name');

function up(opt) {
    if (uping) {
        return;
    }

    $filename.click();
    if (opt && typeof opt.callback === 'function') {
        callback = opt.callback;
    } else {
        callback = '';
    }
}

function getResponse(cb) {
    num = 0;
    inter = setInterval(function() {
        var res = $result[0].contentDocument.body.innerText || '';

        if (num > 20 || res) {
            uping = false;
            $filename.val('');
            clearInterval(inter);
        }

        num++;

        if (res) {
            $result[0].contentDocument.body.innerText = '';
            if (cb) {
                return cb($.parseJSON(res));
            }
        }
    }, 500);
}

$filename.change(function() {
    if ($(this).val()) {
        uping = true;
        $upload.submit();
        getResponse(callback);
    }
});

exports.up = up;