Home
PHP
Tech Tube
MySQL
Linux
CSS&HTML
JavaScript

jQuery AJAX uploader

jQuery plugin that allows easy implementation of AJAX upload. There are multiple callbacks available ;) Simple usage example:
    $('#file_input').samis_uploader({
	//csrf_token: the-crf-token,
	upload_url: '/upload-to-url',
	content_type: 'application/json',
	data_type: 'json',
	success_function: function(upload_result){
		console.log(upload_result);
	},
	progress_function: function(progress_percent){
	    //console.log('Progress: "'+progress_percent+'"');
	},
	before_function: function(e){
	    //console.log('Before:');
	    //console.log(e);
	},
	error_function: function(e){
	    alert('Unknown error!');
	},
    });
    $('.upload_btn').click(function() {
	    $(this).prev().click();
	    return false;
    });
/**
* Sami's AJAX uploader v.1.1
* Handles ajax uploads
* NOTE: requires jQuery
* @param object element - The object that contains the plugin setings
* @author Samuil Banti - https://samiwell.eu
* @copyright (C) 2016 - Samuil Banti
* @license GNU/GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
* @return false. This plugin is focused on the result in the callback methods.
*/
(function( $ ){
    
    $.fn.samis_uploader = function( options ) {
        // Create some defaults, extending them with any options that were provided
        var settings = $.extend( {
			csrf_token: false, // (Optional) You may set the value of the CSRF token input as it should be passed to the upload URL.
			upload_url: false, // The URL that will handle the uploads.
			content_type: false, // Add JSON or something else that you expect as a result.
			data_type: false, // Set the dataType. Most likely JSON.
			success_function: false, // The callback function for success. Gets as parameter the response of the upload URL.
			progress_function: false, // The callback function that get's as parameter the percent of the upload.
			before_function: false, // The callback function to execute before the upload.
			error_function: false, // The callback function to execute in case of HTTP error.
			max_size: 10, // Max upload size in MB (set to false for no frontend limit)
			max_size_error: {success: false, msg: "Max size is 10 MB"} // The response for max file size
        }, options);

        return this.change(function() {
            $.fn.samis_uploader.settings = settings;
            uploader($(this));
        });

        function uploader(element) {
	    var file_contents = element.get(0).files[0];
	    var formData = new FormData();
	    formData.append(element.attr('name'), file_contents);

		if (settings.max_size) {
			const fsize = file_contents.size;
			const file = Math.round((fsize / 1024 / 1024));
			if (file >= settings.max_size) {
				settings.error_function(settings.max_size_error);
				return;
			}
		}
		
	    $.ajax({
			headers: {
			'X-CSRF-Token': settings.csrf_token
			},
			xhr: function() {
				var xhr = new window.XMLHttpRequest();
				xhr.upload.addEventListener("progress", function(evt) {
				if (evt.lengthComputable) {
					var percentComplete = evt.loaded / evt.total;
					if(settings.progress_function) {
					settings.progress_function(Math.floor(percentComplete*100));
					}
				}
				}, false);
				xhr.addEventListener("progress", function(evt) {
				if (evt.lengthComputable) {
					var percentComplete = evt.loaded / evt.total;
					//Do something with download progress
				}
				}, false);
				return xhr;
			},

			url: settings.upload_url,
			//Ajax events
			beforeSend: function (e) {
				if(settings.before_function) {
				settings.before_function(e);
				}
			},
			success: function (e) {
				if(settings.success_function) {
				settings.success_function(e);
				}
			},
			error: function (e) {
				if(settings.error_function) {
				settings.error_function(e);
				}
			},
			// Form data
			data: formData,
			type: 'POST',
			//Options to tell jQuery not to process data or worry about content-type.
			cache: false,
			contentType: settings.content_type,
			dataType: settings.data_type,
			processData: false
	    });
	    element.val(''); // Clear the input value so that the same file could be uploaded
	    return false;
        }

    };
    
})( jQuery );
Download...