EnVisageOnline/Main-RMO/Source/EnVisage/Scripts/Plugins/uploadFile.js

224 lines
7.8 KiB
JavaScript

/* ===========================================================
* UploadFile.js v0.0.1
* ===========================================================
* Copyright 2015 Prevu
* ========================================================== */
(function ($) {
"use strict"; // jshint ;_;
/* UploadFile CLASS DEFINITION
* ====================== */
var UploadFile = function (element, options) {
this.init(element, options);
};
UploadFile.prototype = {
constructor: UploadFile,
init: function(element, options) {
var plugin = this;
this.$options = options;
this.$container = $(element);
this.$input = $(element).find('input[type=file]');
this.$dataset = [];
if (!plugin.$input.length || plugin.$input.length == 0) {
throw "Required input file control was not found. Init upload file control cannot be performed.";
}
if (!plugin.$options.uploadUrl) {
throw "Required upload URL not set. Init upload file control cannot be performed.";
}
if (!plugin.$options.getContentUrl) {
throw "Required get content URL not set. Init upload file control cannot be performed.";
}
this.$table = $("<table class='table table-striped table-bordered' style='display: none;'>" +
"<thead><tr>" +
"<th>Name</th>" +
"<th>Size</th>" +
"<th>Actions</th>" +
"</tr></thead>" +
"</table>").appendTo(plugin.$container);
this.$progress = plugin.$container.find('.progress-bar');
this.$input.fileupload({
url: plugin.$options.uploadUrl,
dataType: 'json',
autoUpload: true,
singleFileUploads: false,
limitMultiFileUploads: 5,
done: function (e, data) {
$.each(data.result, function (index, file) {
plugin.addFile(file);
if (typeof plugin.$options.uploadCallback === 'function') {
plugin.$options.uploadCallback(file);
}
});
},
fail: function (e, data) {
showErrorModal('Attachment uploading error', 'We are sorry but there was an error of uploading file to the server, please try again later. If the error continues, contact administrators to fix the problem');
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
plugin.$progress.css(
'width',
progress + '%'
);
},
start: function (e) {
plugin.$progress.css('width', '0%');
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
// append data from currently rendered HTML nodes
$.each(this.$container.find("[data-uf-file]"), function (index, obj) {
var file = {
Id: $(obj).find('[data-uf-file-id]').val(),
Name: $(obj).find('[data-uf-file-name]').val(),
Size: $(obj).find('[data-uf-file-size]').val(),
IsNew: $(obj).find('[data-uf-file-isnew]').val()
};
plugin.$dataset.push(file);
plugin.renderRow(file);
});
if (typeof this.$options.initCallback === 'function') {
this.$options.initCallback(this.$dataset);
}
return true;
},
addFile: function (obj) {
if (!this.$dataset) {
throw "Dataset not set. Add file operation cannot be performed.";
}
var fileIndex = this.$dataset.length;
var nameElement = this.$input.attr('data-uf-name-template');
this.$dataset.push(obj);
var fileContainer = $('<div data-uf-file="' + obj.Id + '"/>').appendTo(this.$container);
$('<input type="hidden" name="' + nameElement + '[' + fileIndex + '].Id" data-uf-file-id value="' + obj.Id + '">').appendTo(fileContainer);
$('<input type="hidden" name="' + nameElement + '[' + fileIndex + '].Name" data-uf-file-name value="' + obj.Name + '">').appendTo(fileContainer);
$('<input type="hidden" name="' + nameElement + '[' + fileIndex + '].Size" data-uf-file-size value="' + obj.Size + '">').appendTo(fileContainer);
$('<input type="hidden" name="' + nameElement + '[' + fileIndex + '].IsNew" data-uf-file-isnew value="' + obj.IsNew + '">').appendTo(fileContainer);
this.renderRow(obj);
},
renderRow: function(file) {
var plugin = this;
var row = $('<tr id="' + file.Id + '"></tr>');
$('<td></td>').append("<a href='" + this.$options.getContentUrl + "/" + file.Id + "' target='_blank'>" + file.Name + "</a>").appendTo(row);
$('<td></td>').append(plugin.formatFileSize(file.Size)).appendTo(row);
$('<td></td>').append("<a href='javascript:void(0);' class='deleteAttachmentLnk'>Delete</a>").appendTo(row);
this.$table.append(row);
this.$table.css("display", "");
$(row).find('a.deleteAttachmentLnk').on('click', function () {
plugin.removeFile(file.Id);
});
},
formatFileSize: function (sizeBytes) {
if (sizeBytes < 1024)
return sizeBytes + " bytes";
if (sizeBytes < 1024 * 1024)
return (Math.round(sizeBytes / 1024)) + " kb";
return (Math.round(sizeBytes / (1024 * 1024))) + "Mb";
},
removeFile: function (fileId) {
var plugin = this;
var foundIndex = -1;
if (!this.$dataset) {
throw "Dataset not set. Add file operation cannot be performed.";
}
bootbox.confirm("Are you sure want to remove the attachment?", function(result) {
if (result) {
for (var index = 0; index < plugin.$dataset.length; index++) {
if (plugin.$dataset[index].Id == fileId) {
foundIndex = index;
$.ajax({
url: plugin.$options.deleteUrl,
type: 'post',
data: { id: fileId },
success: function (data) {
if (typeof plugin.$options.removeCallback === 'function') {
plugin.$options.removeCallback(fileId);
}
plugin.$dataset.splice(foundIndex, 1);
plugin.$container.find('[data-uf-file=' + fileId + ']').remove();
plugin.$table.find('tr#' + fileId).remove();
if (plugin.$dataset.length < 1) {
plugin.$table.css("display", "none");
} else
plugin.reenumerateAttachments();
},
error: function(ret) {
if (ret.status == 404)
showErrorModal('Attachment deleting error', 'We are sorry but there was an error of deleting file on the server. File not found');
else
showErrorModal('Attachment deleting error', 'We are sorry but there was an error of deleting file on the server, please try again later. If the error continues, contact administrators to fix the problem');
}
});
break;
}
}
}
});
},
reenumerateAttachments: function() {
var namePartTemplate = this.$input.attr('data-uf-name-template');
this.$container.find('[data-uf-file]').each(function (index, item) {
$(this).find('[data-uf-file-id]').prop('name', namePartTemplate + "[" + index + "].Id");
$(this).find('[data-uf-file-name]').prop('name', namePartTemplate + "[" + index + "].Name");
$(this).find('[data-uf-file-size]').prop('name', namePartTemplate + "[" + index + "].Size");
$(this).find('[data-uf-file-isnew]').prop('name', namePartTemplate + "[" + index + "].IsNew");
});
},
destroy: function() {
var e = $.Event('destroy');
this.$container.trigger(e);
if (e.isDefaultPrevented())
return;
this.$container
.off('.uploadFile')
.removeData('uploadFile');
}
};
/* UploadFile PLUGIN DEFINITION
* ======================= */
$.fn.uploadFile = function (option, args) {
return this.each(function() {
var $this = $(this),
data = $this.data('uploadFile'),
options = $.extend({}, $.fn.uploadFile.defaults, $this.data(), typeof option == 'object' && option);
if (!data) $this.data('uploadFile', (data = new UploadFile(this, options)));
if (typeof option == 'string')
data[option].apply(data, [].concat(args));
});
};
$.fn.uploadFile.defaults = {
uploadUrl: null,
deleteUrl: null,
getContentUrl: null,
initCallback: null,
uploadCallback: null,
removeCallback: null
};
$.fn.uploadFile.Constructor = UploadFile;
}(jQuery));