socialforge/public/javascripts/jq-upload/upload.js

62 lines
1.9 KiB
JavaScript
Raw Normal View History

$(function() {
var $upload_file = $('.upload_file');
2015-05-15 17:35:24 +08:00
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
var validateImage = function(file) {
var types = $upload_file.attr('data-file-type').split(",");
var check = false;
$.each(types, function(n, e) {
if (endsWith(file.name, e)) {
check = true;
}
});
if (!check) {
alert($upload_file.attr("data-type-support-message") + $upload_file.attr("data-file-type"));
return false;
}
if (file.size && file.size > parseInt($upload_file.attr('data-max-file-size'))) {
alert($upload_file.attr("data-max-file-size-message"));
return false;
}
return true;
2015-05-15 16:18:44 +08:00
};
$('.upload_file').fileupload({
url: '/upload_avatar.json?source_type=' + $('.upload_file').attr('data-source-type') +
'&source_id=' + $('.upload_file').attr('data-source-id'),
2015-05-15 17:35:24 +08:00
add: function(e, data) {
if (!validateImage(data.files[0])) {
return false;
}
data.submit();
2015-05-15 16:18:44 +08:00
},
formData: function(form) {
var data = form.serializeArray();
var auth = null;
2015-05-15 17:35:24 +08:00
for (var key in data) {
if (data[key].name == "authenticity_token") {
auth = data[key];
break;
}
}
return [auth];
},
done: function(e, data) {
var imgSpan = jQuery('#avatar_image');
var result = data.result.text ? data.result.text() : data.result;
if(result){
var o = JSON.parse(result);
if(o.status == 0){
imgSpan.attr({
"src": o.url
});
} else {
alert(o.message);
}
}
}
});
});