Multiple Image File Upload dengan Plugin Jquery File Upload dan Codeigniter 3
Tutorial Implementasi Multiple Image File Upload dengan Jquery File Upload dan Codeigniter 3 [docs/kuhomi.id].

Multiple Image File Upload dengan Plugin Jquery File Upload dan Codeigniter 3

Pada artikel sebelumnya, gua sharing mengenai cara Cara Upload dan Resize File dengan Menggunakan Codeigniter dan GD2. Nah pada artikel ini, gua mau coba sharing mengenai cara membuat multiple upload file image menggunakan plugin Jquery File Upload dan Codeigniter 3.

Oke, langsung aja gimana kodingannya.

Sebelum lanjut ke kodingan, gua mau jelasin dulu batasan pada tutorial kali ini. Pada tutorial kali ini, belum menggunakan koneksi database untuk menyimpan path atau metadata image yang di upload ya..jadi, hanya proses upload dari device kita ke server web. Dan disini gua juga tidak menjelaskan bagaimana config dasar Codeigniter 3. 

1. Persiapan Bahan

Download file plugin Jquery File Upload melalui link ini : Download Jquery File Upload.

File hasil download berupa .zip. Unzip file tersebut. Untuk mempermudah proses koding nanti, rename folder hasil unzip tadi dengan nama yang menurut kalian lebih mudah diketik (hehehe). Kalo gua, disini gua rename menjadi "jquery-multiple-file-upload".

Selanjutnya, copy folder tersebut ke dalam projek Codeigniter kalian. Kalo gua, disini gua letakkan di folder "/assets/plugins/"

kuhomi.id

2. Buat File View

  • Load file-file css dan script jquery, bootstrap serta plugin file upload dibawah ini pada tag head
<title>Tutorial Multiple Upload Image with Jquery File Upload</title>
<!-- load script package jquery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!-- Bootstrap CSS -->
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css'>
<!-- Bootstrap JS -->
<script src="https://cdn.usebootstrap.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
        
<!-- Load file CSS plugin jquery-file-upload -->
<link rel="stylesheet" href="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/css/jquery.fileupload.css" />
<link rel="stylesheet" href="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/css/jquery.fileupload-ui.css" />
<link rel="stylesheet" href="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/css/demo.css" />
<!-- style untuk mengatasi class fade tidak bisa menampilkan list preview image -->
<style type="text/css">
   .fade.in {
             opacity: 1
            }
</style>
  • Selanjutnya, buat form untuk tampilan multiple upload file
<form id="fileupload" action="/files_upload/proses_uploads/" method="POST" enctype="multipart/form-data">
	<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
	<div class="row fileupload-buttonbar">
		<div class="col-lg-7">
		<!-- The fileinput-button span is used to style the file input field as button -->
			<span class="btn btn-success fileinput-button">
				<i class="glyphicon glyphicon-plus"></i>
				<span>Add files...</span>
				<input type="file" name="files" multiple />
			</span>
			<button type="submit" class="btn btn-primary start">
				<i class="glyphicon glyphicon-upload"></i>
				<span>Start upload</span>
			</button>
			<button type="reset" class="btn btn-warning cancel">
				<i class="glyphicon glyphicon-ban-circle"></i>
				<span>Cancel upload</span>
			</button>
			<button type="button" class="btn btn-danger delete">
				<i class="glyphicon glyphicon-trash"></i>
				<span>Delete selected</span>
			</button>
			<input type="checkbox" class="toggle" />
			<!-- The global file processing state -->
			<span class="fileupload-process"></span>
		</div>
		<!-- The global progress state -->
		<div class="col-lg-5 fileupload-progress fade">
		 <!-- The global progress bar -->
			<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
				<div class="progress-bar progress-bar-success" style="width:0%;"></div>
			</div>
			<!-- The extended global progress state -->
			<div class="progress-extended"> </div>
		</div>
	</div>
	<!-- The table listing the files available for upload/download -->
	<table role="presentation" class="table table-striped">
		<tbody class="files"></tbody>
	</table>
</form
  • Lalu, di bawah tag form, tambahkan script template dalam bentuk text x-tmpl untuk menampilkan list file yang siap untuk di upload serta template list file yang dapat di unduh (file yang sudah diupload ke server)
<!-- The template to display files available for upload -->
	<script id="template-upload" type="text/x-tmpl">
		{% for (var i=0, file; file=o.files[i]; i++) { %}
			<tr class="template-upload fade">
				<td>
					<span class="preview"></span>
				</td>
				<td>
				{% if (window.innerWidth > 480 || !o.options.loadImageFileTypes.test(file.type)) { %}
					<p class="name">{%=file.name%}</p>
				{% } %}
					<strong class="error text-danger"></strong>
				</td>
				<td>
					<p class="size">Processing...</p>
					<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
				</td>
				<td>
					{% if (!o.options.autoUpload && o.options.edit && o.options.loadImageFileTypes.test(file.type)) { %}
						<button class="btn btn-success edit" data-index="{%=i%}" disabled>
							<i class="glyphicon glyphicon-edit"></i>
							<span>Edit</span>
						</button>
					{% } %}
					{% if (!i && !o.options.autoUpload) { %}
						<button class="btn btn-primary start" disabled>
							<i class="glyphicon glyphicon-upload"></i>
							<span>Start</span>
						</button>
					{% } %}
					{% if (!i) { %}
						<button class="btn btn-warning cancel">
							<i class="glyphicon glyphicon-ban-circle"></i>
							<span>Cancel</span>
						</button>
					{% } %}
				</td>
			</tr>
		{% } %}
	</script>
	<!-- The template to display files available for download -->
	<script id="template-download" type="text/x-tmpl">
		{% for (var i=0, file; file=o.files[i]; i++) { %}
			<tr class="template-download fade">
				<td>
					<span class="preview">
					{% if (file.thumbnailUrl) { %}
						<a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}" width="75px" height="auto"></a>
					{% } %}
					</span>
				</td>
				<td>
					{% if (window.innerWidth > 480 || !file.thumbnailUrl) { %}
						<p class="name">
					{% if (file.url) { %}
						<a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
					{% } else { %}
						<span>{%=file.name%}</span>
					{% } %}
						</p>
					{% } %}
					{% if (file.error) { %}
						<div><span class="label label-danger">Error</span> {%=file.error%}</div>
					{% } %}
				</td>
				<td>
					<span class="size">{%=o.formatFileSize(file.size)%}</span>
				</td>
				<td>
					{% if (file.deleteUrl) { %}
						<button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
							<i class="glyphicon glyphicon-trash"></i>
							<span>Delete</span>
						</button>
						<input type="checkbox" name="delete" value="1" class="toggle">
					{% } else { %}
						<button class="btn btn-warning cancel">
							<i class="glyphicon glyphicon-ban-circle"></i>
							<span>Cancel</span>
						</button>
					{% } %}
				</td>
			</tr>
		{% } %}
	</script>
  • Selanjutnya, load script plugins jquery file upload serta dependencies nya. Perhatikan urutan load nya dan path tempat kalian meletakan plugin jquery file upload ya, karna sangat berpengaruh dan jika urutannya tidak tepat, dapat menyebabkan error.
<!-- load script plugin dan dependencies jquery-file-upload (perhatikan urutan load nya ya) -->
<script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/vendor/jquery.ui.widget.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-JavaScript-Templates/3.20.0/js/tmpl.min.js" integrity="sha512-yQJVqoTPFSC73MaslsQaVJ0zHku4Cby3NpQzweSYju+kduWspfF4HmJ3zAo1QGERfsoXdf45q54ph8XTjOlp8A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-load-image/4.0.1/load-image.all.min.js" integrity="sha512-wq/lJzSqIJiX+m6pSOhNgK/rh04WllSatyeFlqH0+v5jn//RUZTO8RFmqn4fMg3YNTF/xiLlm/MYlN0VA1WLvQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript-canvas-to-blob/3.29.0/js/canvas-to-blob.min.js" integrity="sha512-zkt2aBQ0jhSXjI6VhJegNqBN3Kqlbi7PxpxOpELGoKtRGSuPOVGvetuTixdhQSuRefsFKroRgWRwQDpRcMd3+A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.iframe-transport.js"></script>
<!-- The basic File Upload plugin -->
<script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload.js"></script>
<!-- The File Upload processing plugin -->
<script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-process.js"></script>
<!-- The File Upload image preview & resize plugin -->
<script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-image.js"></script>
<!-- The File Upload audio preview plugin -->
<script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-audio.js"></script>
<!-- The File Upload video preview plugin -->
<script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-video.js"></script>
<!-- The File Upload validation plugin -->
<script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-validate.js"></script>
<!-- The File Upload user interface plugin -->
<script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-ui.js"></script>
  • Selanjutnya, tambahkan script untuk handle proses upload serta validasi dasar, seperti tipe file yang dapat di upload atau filesize maksimal yang dapat di upload
<script type="text/javascript">
	$(function() {
		'use strict';

		// Initialize the jQuery File Upload widget:
		$('#fileupload').fileupload({
			// Uncomment the following to send cross-domain cookies:
			//xhrFields: {withCredentials: true},
			// allowed type file (gif,jpg,jpg,png)
			acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
			// The maximum allowed file size in bytes:
			maxFileSize: 1000000, // 1 MB
			url: '/files_upload/proses_uploads' //path ke controller dan method proses upload
		}).bind('fileuploadadded', function (e, data) {
			console.log(data.files.valid);
		});

		// Enable iframe cross-domain access via redirect option:
		$('#fileupload').fileupload(
			'option',
			'redirect',
			window.location.href.replace(/\/[^/]*$/, '/cors/result.html?%s')
		);

		if (window.location.hostname === 'blueimp.github.io') {
			// Demo settings:
			$('#fileupload').fileupload('option', {
				url: '//jquery-file-upload.appspot.com/',
				// Enable image resizing, except for Android and Opera,
				// which actually support image resizing, but fail to
				// send Blob objects via XHR requests:
				disableImageResize: /Android(?!.*Chrome)|Opera/.test(
					window.navigator.userAgent
				),
				maxFileSize: 999000,
				acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
			});
			// Upload server status check for browsers with CORS support:
			if ($.support.cors) {
				$.ajax({
					url: '/files_upload/proses_uploads',
					type: 'HEAD'
				}).fail(function() {
					$('<div class="alert alert-danger"/>')
					.text('Upload server currently unavailable - ' + new Date())
					.appendTo('#fileupload');
				});
			}
		} else {
			// Load existing files:
			$('#fileupload').addClass('fileupload-processing');
			$.ajax({
				// Uncomment the following to send cross-domain cookies:
				//xhrFields: {withCredentials: true},
				url: $('#fileupload').fileupload('option', 'url'),
				dataType: 'json',
				context: $('#fileupload')[0]
			})
			.always(function() {
				$(this).removeClass('fileupload-processing');
			})
			.done(function(result) {
			$(this)
				.fileupload('option', 'done')
				// eslint-disable-next-line new-cap
				.call(this, $.Event('done'), { result: result });
			});
		}
	});
</script>
  • Untuk full kodingan nya di file views, cek dibawah ini ya
<!DOCTYPE html>
<html>
    <head>
        <title>Tutorial Multiple Upload Image with Jquery File Upload</title>
        <!-- load script package jquery -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <!-- Bootstrap CSS -->
        <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css'>
        <!-- Bootstrap JS -->
        <script src="https://cdn.usebootstrap.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
        
        <!-- Load file CSS plugin jquery-file-upload -->
        <link rel="stylesheet" href="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/css/jquery.fileupload.css" />
        <link rel="stylesheet" href="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/css/jquery.fileupload-ui.css" />
        <link rel="stylesheet" href="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/css/demo.css" />
        <!-- style untuk mengatasi class fade tidak bisa menampilkan list preview image -->
        <style type="text/css">
            .fade.in {
                opacity: 1
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-sm-12">
                    <div class="container-fluid">
                        <div class="box box-info">
                            <div class="box-body pad">
                                <form id="fileupload" action="/files_upload/proses_uploads/" method="POST" enctype="multipart/form-data">
                                    <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
                                    <div class="row fileupload-buttonbar">
                                        <div class="col-lg-7">
                                        <!-- The fileinput-button span is used to style the file input field as button -->
                                            <span class="btn btn-success fileinput-button">
                                                <i class="glyphicon glyphicon-plus"></i>
                                                <span>Add files...</span>
                                                <input type="file" name="files" multiple />
                                            </span>
                                            <button type="submit" class="btn btn-primary start">
                                                <i class="glyphicon glyphicon-upload"></i>
                                                <span>Start upload</span>
                                            </button>
                                            <button type="reset" class="btn btn-warning cancel">
                                                <i class="glyphicon glyphicon-ban-circle"></i>
                                                <span>Cancel upload</span>
                                            </button>
                                            <button type="button" class="btn btn-danger delete">
                                                <i class="glyphicon glyphicon-trash"></i>
                                                <span>Delete selected</span>
                                            </button>
                                            <input type="checkbox" class="toggle" />
                                            <!-- The global file processing state -->
                                            <span class="fileupload-process"></span>
                                        </div>
                                        <!-- The global progress state -->
                                        <div class="col-lg-5 fileupload-progress fade">
                                         <!-- The global progress bar -->
                                            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                                                <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                                            </div>
                                            <!-- The extended global progress state -->
                                            <div class="progress-extended"> </div>
                                        </div>
                                    </div>
                                    <!-- The table listing the files available for upload/download -->
                                    <table role="presentation" class="table table-striped">
                                        <tbody class="files"></tbody>
                                    </table>
                                </form>
                            </div>
                            <div class="clearfix"></div>
                            <!-- END PAGE CONTENT-->

                            <!-- The template to display files available for upload -->
                            <script id="template-upload" type="text/x-tmpl">
                                {% for (var i=0, file; file=o.files[i]; i++) { %}
                                    <tr class="template-upload fade">
                                        <td>
                                            <span class="preview"></span>
                                        </td>
                                        <td>
                                        {% if (window.innerWidth > 480 || !o.options.loadImageFileTypes.test(file.type)) { %}
                                            <p class="name">{%=file.name%}</p>
                                        {% } %}
                                            <strong class="error text-danger"></strong>
                                        </td>
                                        <td>
                                            <p class="size">Processing...</p>
                                            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
                                        </td>
                                        <td>
                                            {% if (!o.options.autoUpload && o.options.edit && o.options.loadImageFileTypes.test(file.type)) { %}
                                                <button class="btn btn-success edit" data-index="{%=i%}" disabled>
                                                    <i class="glyphicon glyphicon-edit"></i>
                                                    <span>Edit</span>
                                                </button>
                                            {% } %}
                                            {% if (!i && !o.options.autoUpload) { %}
                                                <button class="btn btn-primary start" disabled>
                                                    <i class="glyphicon glyphicon-upload"></i>
                                                    <span>Start</span>
                                                </button>
                                            {% } %}
                                            {% if (!i) { %}
                                                <button class="btn btn-warning cancel">
                                                    <i class="glyphicon glyphicon-ban-circle"></i>
                                                    <span>Cancel</span>
                                                </button>
                                            {% } %}
                                        </td>
                                    </tr>
                                {% } %}
                            </script>
                            <!-- The template to display files available for download -->
                            <script id="template-download" type="text/x-tmpl">
                                {% for (var i=0, file; file=o.files[i]; i++) { %}
                                    <tr class="template-download fade">
                                        <td>
                                            <span class="preview">
                                            {% if (file.thumbnailUrl) { %}
                                                <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}" width="75px" height="auto"></a>
                                            {% } %}
                                            </span>
                                        </td>
                                        <td>
                                            {% if (window.innerWidth > 480 || !file.thumbnailUrl) { %}
                                                <p class="name">
                                            {% if (file.url) { %}
                                                <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
                                            {% } else { %}
                                                <span>{%=file.name%}</span>
                                            {% } %}
                                                </p>
                                            {% } %}
                                            {% if (file.error) { %}
                                                <div><span class="label label-danger">Error</span> {%=file.error%}</div>
                                            {% } %}
                                        </td>
                                        <td>
                                            <span class="size">{%=o.formatFileSize(file.size)%}</span>
                                        </td>
                                        <td>
                                            {% if (file.deleteUrl) { %}
                                                <button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                                                    <i class="glyphicon glyphicon-trash"></i>
                                                    <span>Delete</span>
                                                </button>
                                                <input type="checkbox" name="delete" value="1" class="toggle">
                                            {% } else { %}
                                                <button class="btn btn-warning cancel">
                                                    <i class="glyphicon glyphicon-ban-circle"></i>
                                                    <span>Cancel</span>
                                                </button>
                                            {% } %}
                                        </td>
                                    </tr>
                                {% } %}
                            </script>
                        </div>
                    </div>
                </div>
            </div>
        </div>
            
        <!-- load script plugin dan dependencies jquery-file-upload (perhatikan urutan load nya ya) -->
        <script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/vendor/jquery.ui.widget.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-JavaScript-Templates/3.20.0/js/tmpl.min.js" integrity="sha512-yQJVqoTPFSC73MaslsQaVJ0zHku4Cby3NpQzweSYju+kduWspfF4HmJ3zAo1QGERfsoXdf45q54ph8XTjOlp8A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        
        <script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-load-image/4.0.1/load-image.all.min.js" integrity="sha512-wq/lJzSqIJiX+m6pSOhNgK/rh04WllSatyeFlqH0+v5jn//RUZTO8RFmqn4fMg3YNTF/xiLlm/MYlN0VA1WLvQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/javascript-canvas-to-blob/3.29.0/js/canvas-to-blob.min.js" integrity="sha512-zkt2aBQ0jhSXjI6VhJegNqBN3Kqlbi7PxpxOpELGoKtRGSuPOVGvetuTixdhQSuRefsFKroRgWRwQDpRcMd3+A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

        <script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.iframe-transport.js"></script>
        <!-- The basic File Upload plugin -->
        <script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload.js"></script>
        <!-- The File Upload processing plugin -->
        <script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-process.js"></script>
        <!-- The File Upload image preview & resize plugin -->
        <script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-image.js"></script>
        <!-- The File Upload audio preview plugin -->
        <script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-audio.js"></script>
        <!-- The File Upload video preview plugin -->
        <script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-video.js"></script>
        <!-- The File Upload validation plugin -->
        <script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-validate.js"></script>
        <!-- The File Upload user interface plugin -->
        <script src="<?php echo base_url() ?>assets/plugins/jquery-multiple-file-upload/js/jquery.fileupload-ui.js"></script>
        
        <script type="text/javascript">
            $(function() {
                'use strict';

                // Initialize the jQuery File Upload widget:
                $('#fileupload').fileupload({
                    // Uncomment the following to send cross-domain cookies:
                    //xhrFields: {withCredentials: true},
                    // allowed type file (gif,jpg,jpg,png)
                    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
                    // The maximum allowed file size in bytes:
                    maxFileSize: 1000000, // 1 MB
                    url: '/files_upload/proses_uploads' //path ke controller dan method proses upload
                }).bind('fileuploadadded', function (e, data) {
                    console.log(data.files.valid);
                });

                // Enable iframe cross-domain access via redirect option:
                $('#fileupload').fileupload(
                    'option',
                    'redirect',
                    window.location.href.replace(/\/[^/]*$/, '/cors/result.html?%s')
                );

                if (window.location.hostname === 'blueimp.github.io') {
                    // Demo settings:
                    $('#fileupload').fileupload('option', {
                        url: '//jquery-file-upload.appspot.com/',
                        // Enable image resizing, except for Android and Opera,
                        // which actually support image resizing, but fail to
                        // send Blob objects via XHR requests:
                        disableImageResize: /Android(?!.*Chrome)|Opera/.test(
                            window.navigator.userAgent
                        ),
                        maxFileSize: 999000,
                        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
                    });
                    // Upload server status check for browsers with CORS support:
                    if ($.support.cors) {
                        $.ajax({
                            url: '/files_upload/proses_uploads',
                            type: 'HEAD'
                        }).fail(function() {
                            $('<div class="alert alert-danger"/>')
                            .text('Upload server currently unavailable - ' + new Date())
                            .appendTo('#fileupload');
                        });
                    }
                } else {
                    // Load existing files:
                    $('#fileupload').addClass('fileupload-processing');
                    $.ajax({
                        // Uncomment the following to send cross-domain cookies:
                        //xhrFields: {withCredentials: true},
                        url: $('#fileupload').fileupload('option', 'url'),
                        dataType: 'json',
                        context: $('#fileupload')[0]
                    })
                    .always(function() {
                        $(this).removeClass('fileupload-processing');
                    })
                    .done(function(result) {
                    $(this)
                        .fileupload('option', 'done')
                        // eslint-disable-next-line new-cap
                        .call(this, $.Event('done'), { result: result });
                    });
                }
            });
        </script>
    </body>
</html>

3. Selanjutnya, kita buat class Controller nya seperti berikut

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Files_upload extends CI_Controller {

	public function index()
	{
		//load file view yang telah dibuat sebelumnya
		$this->load->view('files_management/form_multi_upload');
	}

	public function proses_uploads()
    {
    	//path direktori dan url lokasi simpan file upload
		$directory = "./assets/img/gallery";
		$upload_path_url = "/assets/img/gallery/";
		//deklarasi filename file upload supaya unik
		$file_name = time().rand(pow(10, 2), pow(10, 3)-1);
		//fungsi untuk membuat directory jika directory belum dibuat
		if (!is_dir($directory)) {
    		mkdir($directory, 0775, TRUE);
		}

		//configurasi library upload
		//set path tempat simpan file upload
		$config['upload_path']=$directory;
		//tipe file yang diperbolehkan untuk diupload
        $config['allowed_types']='gif|jpg|png|jpeg';
        $config['encrypt_name'] = FALSE;
        //file name photo, jika diset maka filename foto diubah sesuai dengan apa yang dideklarasikan
        $config['file_name'] = $file_name;
         
        //load library upload beserta config nya
        $this->load->library('upload',$config);
        //proses upload
        if($this->upload->do_upload("files")){
            $data = array('upload_data' => $this->upload->data());
            	
            //set data info image yang diupload
            $info = new stdClass();
            $info->name = $data['upload_data']['file_name'];
            $info->size = $data['upload_data']['file_size'];
            $info->type = $data['upload_data']['file_type'];
            $info->url = $upload_path_url . $data['upload_data']['file_name'];
            $info->thumbnailUrl = $upload_path_url . $data['upload_data']['file_name'];
            $info->deleteUrl = '/files_upload/delete/?file=' . $data['upload_data']['file_name'];
            $info->deleteType = 'DELETE';
            $info->error = null;

            //input data info image ke variable array dengan nama $files
            $files[] = $info;
            
			//return ke pemanggilnya yaitu ajax
            echo json_encode(array("files" => $files));
        }
        else
        {	
        	//kondisi else jika ingin menampilkan image yang telah diupload sebelumnya
            //Load list file image yang ada di directory upload
            $existingFiles = get_dir_file_info($config['upload_path']);
            $foundFiles = array();
            $f=0;
            //set data image yang ada di directory upload ke dalam variable array dan di enode ke json
            foreach ($existingFiles as $fileName => $info) {
                $foundFiles[$f]['name'] = $fileName;
                $foundFiles[$f]['size'] = $info['size'];
                $foundFiles[$f]['url'] = '/assets/img/gallery/' . $fileName;
                $foundFiles[$f]['thumbnailUrl'] = '/assets/img/gallery/' . $fileName;
                $foundFiles[$f]['deleteUrl'] = '/files_upload/delete/?file=' . $fileName;
                $foundFiles[$f]['deleteType'] = 'DELETE';
                $foundFiles[$f]['error'] = null;
                $f++;
            }
            $this->output->set_content_type('application/json')->set_output(json_encode(array('files' => $foundFiles)));
        } 
    }

    //fungsi untuk hapus file image yang ada di directory upload
    public function delete()
    {
        $file = $this->input->get('file');
        $directory = "./assets/img/gallery/";
        $success = unlink($directory.$file);

        //info to see if it is doing what it is supposed to
        $info = new stdClass();
        $info->sucess = $success;
        $info->path = '/assets/img/gallery/'.$file;
        $info->file = is_file($directory.$file);
        
        echo json_encode(array($info));
    }
}

dan berikut capture hasil implementasinya

Preview Hasil Implementasi Jquery File Upload

Artikel Terkait