Membuat Upload File dengan Progress bar (PHP, MySQL, AJAX, Bootstrap).
Hai sobat SilaenTech, kali ini saya akan membuat sebuah tutorial
tentang cara membuat Upload file dengan progress bar, tentu saja
menggunakan PHP untuk bahasa pemrogramannya, MySQL sebagai databasenya,
AJAX untuk menghandle progress barnya, dan Bootstrap untuk interfacenya
biar cantik…
Nanti kita akan membuat file berikut ini sob:
- index.php (untuk tampilan awal, form dan progress bar)
- config.php (koneksi ke database)
- upload.php (proses upload file, menyimpan data ke database)
- upload.js (untuk handle progress bar)
Download Bootstrap
Pertama karena ini menggunakan Bootstrap untuk interfacenya, maka
silahkan download dulu Bootstrap di webseite resminya, atau bisa klik disini. Saya masih menggunakan yang versi 3 ya.
Nah, selesai di download maka sobat akan mendapatkan file bootstrap-3.3.7-dist.zip. Silahkan di ekstrak menggunakan winrar/winzip atau sejenisnya, maka sobat akan mendapatkan 3 folder utama, yaitu css, font, dan js.
Masukkan 3 folder tersebut kedalam folder misal dengan nama upload-progressbar, dan masukkan di folder htdocs pada web server localnya (C:\xampp\htdocs\uploadprogressbar), nah jika sudah maka kita lanjutkan ke tahap selanjutnya.
Membuat Database dan Table
Untuk membuat database silahkan masuk ke alamat localhost/phpmyadmin,
kemudian buat database baru dengan nama tutorialweb_upload_progressbar,
jika sudah masuk ke menu SQL, dan copy paste kode di bawah ini:
CREATE TABLE `files` (
`id` int(11) NOT NULL,
`tgl_upload` date NOT NULL,
`file_name` varchar(50) NOT NULL,
`file_size` int(20) NOT NULL,
`file_type` varchar(5) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
`id` int(11) NOT NULL,
`tgl_upload` date NOT NULL,
`file_name` varchar(50) NOT NULL,
`file_size` int(20) NOT NULL,
`file_type` varchar(5) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
sobat akan mendapatkan sebuah tabel dengan nama files.
Untuk database saya rasa cukup, dan kita lanjutkan ke tahap selanjutnya.
Membuat koneksi ke database
Mudah saja sob, silahkan copy paste kode di bawah ini ya, dan simpan dengan nama config.php
<?php
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
session_start();
//melakukan koneksi ke database
$conn = new mysqli("localhost", "root", "", "dbgbr");
if ($conn->connect_errno) {
echo die("Gagal Koneksi Database: " . $conn->connect_error);
}
?>
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
session_start();
//melakukan koneksi ke database
$conn = new mysqli("localhost", "root", "", "dbgbr");
if ($conn->connect_errno) {
echo die("Gagal Koneksi Database: " . $conn->connect_error);
}
?>
Silahkan ganti koneksinya sesuai dengan server sobat sendiri ya.
Membuat Halaman index.php (form upload & progress bar)
Untuk halaman index.php tidak banyak yang bisa dijelaskan, silahkan copy paste kode di bawah ini, kemudian simpan dengan nama index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Upload file progress bar dengan PHP dan MySQL">
<meta name="author" content="fatoni arif">
<title>Upload File dengan PHP, MySQL dan Bootstrap</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" style="margin-top:200px;">
<div class="well text-center">
<h1>Upload file dengan cepat!</h1>
<hr>
<div class="col-md-8 col-md-offset-2">
<form class="form-inline" method="post" action="">
<div class="input-group">
<label class="input-group-btn">
<span class="btn btn-danger btn-lg">
Browse… <input type="file" id="media" name="media" style="display: none;" required>
</span>
</label>
<input type="text" class="form-control input-lg" size="40" readonly required>
</div>
<div class="input-group">
<input type="submit" class="btn btn-lg btn-primary" value="Start upload">
</div>
</form>
<br>
<div class="progress" style="display:none">
<div id="progressBar" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
<span class="sr-only">0%</span>
</div>
</div>
<div class="msg alert alert-info text-left" style="display:none"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/upload.js"></script>
<script>
$(function() {
$(document).on('change', ':file', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready( function() {
$(':file').on('fileselect', function(event, numFiles, label) {
var input = $(this).parents('.input-group').find(':text'),
log = numFiles > 1 ? numFiles + ' files selected' : label;
if( input.length ) {
input.val(log);
} else {
if( log ) alert(log);
}
});
});
});
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Upload file progress bar dengan PHP dan MySQL">
<meta name="author" content="fatoni arif">
<title>Upload File dengan PHP, MySQL dan Bootstrap</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" style="margin-top:200px;">
<div class="well text-center">
<h1>Upload file dengan cepat!</h1>
<hr>
<div class="col-md-8 col-md-offset-2">
<form class="form-inline" method="post" action="">
<div class="input-group">
<label class="input-group-btn">
<span class="btn btn-danger btn-lg">
Browse… <input type="file" id="media" name="media" style="display: none;" required>
</span>
</label>
<input type="text" class="form-control input-lg" size="40" readonly required>
</div>
<div class="input-group">
<input type="submit" class="btn btn-lg btn-primary" value="Start upload">
</div>
</form>
<br>
<div class="progress" style="display:none">
<div id="progressBar" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
<span class="sr-only">0%</span>
</div>
</div>
<div class="msg alert alert-info text-left" style="display:none"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/upload.js"></script>
<script>
$(function() {
$(document).on('change', ':file', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready( function() {
$(':file').on('fileselect', function(event, numFiles, label) {
var input = $(this).parents('.input-group').find(':text'),
log = numFiles > 1 ? numFiles + ' files selected' : label;
if( input.length ) {
input.val(log);
} else {
if( log ) alert(log);
}
});
});
});
</script>
</body>
</html>
Membuat file upload.php
Oke sob, file upload.php ini gunanya untuk menghandle proses upload mulai dari menyimpan data ke database sampai menyalin file tersebut ke folder files. Dan berikut ini kodenya;
<?php
//memasukkan file config.php
include("config.php");
//mendefinisikan folder upload
define("UPLOAD_DIR", "files/");
if (!empty($_FILES["media"])) {
$media = $_FILES["media"];
$ext = pathinfo($_FILES["media"]["name"], PATHINFO_EXTENSION);
$size = $_FILES["media"]["size"];
$tgl = date("Y-m-d");
if ($media["error"] !== UPLOAD_ERR_OK) {
echo '<div class="alert alert-warning">Gagal upload file.</div>';
exit;
}
// filename yang aman
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $media["name"]);
// mencegah overwrite filename
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
$success = move_uploaded_file($media["tmp_name"], UPLOAD_DIR . $name);
if ($success) {
$in = $conn->query("INSERT INTO files(tgl_upload, file_name, file_size, file_type) VALUES('$tgl', '$name', '$size', '$ext')");
$q = $conn->query("SELECT id FROM files ORDER BY id DESC LIMIT 1");
$rq = $q->fetch_assoc();
echo $rq['id'];
exit;
}
chmod(UPLOAD_DIR . $name, 0644);
}
?>
//memasukkan file config.php
include("config.php");
//mendefinisikan folder upload
define("UPLOAD_DIR", "files/");
if (!empty($_FILES["media"])) {
$media = $_FILES["media"];
$ext = pathinfo($_FILES["media"]["name"], PATHINFO_EXTENSION);
$size = $_FILES["media"]["size"];
$tgl = date("Y-m-d");
if ($media["error"] !== UPLOAD_ERR_OK) {
echo '<div class="alert alert-warning">Gagal upload file.</div>';
exit;
}
// filename yang aman
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $media["name"]);
// mencegah overwrite filename
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
$success = move_uploaded_file($media["tmp_name"], UPLOAD_DIR . $name);
if ($success) {
$in = $conn->query("INSERT INTO files(tgl_upload, file_name, file_size, file_type) VALUES('$tgl', '$name', '$size', '$ext')");
$q = $conn->query("SELECT id FROM files ORDER BY id DESC LIMIT 1");
$rq = $q->fetch_assoc();
echo $rq['id'];
exit;
}
chmod(UPLOAD_DIR . $name, 0644);
}
?>
Penjelasan kode sebagian sudah saya masukkan di scriptnya, kalau kurang jelas bisa komentar ya.
Membuat file upload.js
File upload.js ini berfungsi untuk menghandle progress barnya, hingga
memunculkan pesan ID terakhir yang masuk ke database, berikut ini
script lengkapnya:
$(document).ready(function() {
$('form').on('submit', function(event){
event.preventDefault();
var formData = new FormData($('form')[0]);
$('.msg').hide();
$('.progress').show();
$.ajax({
xhr : function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e){
if(e.lengthComputable){
console.log('Bytes Loaded : ' + e.loaded);
console.log('Total Size : ' + e.total);
console.log('Persen : ' + (e.loaded / e.total));
var percent = Math.round((e.loaded / e.total) * 100);
$('#progressBar').attr('aria-valuenow', percent).css('width', percent + '%').text(percent + '%');
}
});
return xhr;
},
type : 'POST',
url : 'upload.php',
data : formData,
processData : false,
contentType : false,
success : function(response){
$('form')[0].reset();
$('.progress').hide();
$('.msg').show();
if(response == ""){
alert('File gagal di upload');
}else{
var msg = 'File berhasil di upload. ID file = ' + response;
$('.msg').html(msg);
}
}
});
});
});
$('form').on('submit', function(event){
event.preventDefault();
var formData = new FormData($('form')[0]);
$('.msg').hide();
$('.progress').show();
$.ajax({
xhr : function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e){
if(e.lengthComputable){
console.log('Bytes Loaded : ' + e.loaded);
console.log('Total Size : ' + e.total);
console.log('Persen : ' + (e.loaded / e.total));
var percent = Math.round((e.loaded / e.total) * 100);
$('#progressBar').attr('aria-valuenow', percent).css('width', percent + '%').text(percent + '%');
}
});
return xhr;
},
type : 'POST',
url : 'upload.php',
data : formData,
processData : false,
contentType : false,
success : function(response){
$('form')[0].reset();
$('.progress').hide();
$('.msg').show();
if(response == ""){
alert('File gagal di upload');
}else{
var msg = 'File berhasil di upload. ID file = ' + response;
$('.msg').html(msg);
}
}
});
});
});
simpannya di folder js ya sob, beri nama upload.js
Sudah deh selesai. sekarang bisa sobat coba sendiri di rumah.
sumber : tutorialweb.net
Tidak ada komentar:
Write komentar