jQuery Ajax File Upload
PHP ile dosya yükleme işlemi yaparken kullanıcılara Upload durumunun hangi aşamada olduğunu yüzdesel olarak veya bir progres bar ile göstermek elbette daha güzel olur.
jQuery Form plugini ile bu işi basitçe yapabiliyoruz. Bu yazımızda php ile bir upload sayfası hazırlayıp jQuery Form ile progres bar da durumunu gösterelim.
Kısaca jQuery Form plugini nedir? ne değildir bir bakalım.
jQuery Form Plugini Kullanımı
$('#formid').ajaxForm(function() {
alert("Form gönderildi.");
});
Daha farklı bir Kullanım
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
success: afterSuccess, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
resetForm: true // reset the form after successful submit
};
$('#MyUploadForm').submit(function () {
$(this).ajaxSubmit(options);
return false;
});
});
ajaxForm a parametre göndererek işlemimizin durumuna göre ne istersek yapabiliyoruz.
beforeSend | fonksiyonu upload işlemi başlamadan önce yapmak istediğimiz işlemler için | |
uploadProgress | fonksiyonu upload işlemimiz devam ederken çalışıyor | |
success | form başarılı bir şekilde upload edildiyse çalışıyor | |
complate | fonksiyonu ise işlem bittiğinde tetikleniyor. |
Upload Formu
Şimdi dosya yükleme için kullanacağımız basit bir form tasarlayalım.
<input type="file" name="dosya">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="yuzde">0%</div >
</div>
<br/>
<div id="mesaj"></div>
beforeSend kısmında bar genişliğini %0 olarak ayarlayoruz ve yuzde divine %0 yazdırıyoruz.
uploadProgress te percentComplate ile işlemin yüzdesini alıyoruz ve bar id li div e genişlik olarak veriyoruz.
success olunca hepsini %100 yapıyoruz.
complate fonksiyonunda ise mesaj kısmına başarılı yazdırıyoruz.
eğer bir hata olduysa da error fonksiyonunda hata olarak belirtelim.
Jquery Kodları
$("#dosyayukle").ajaxForm({
beforeSend: function(){
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#mesaj").html("");
$("#yuzde").html("0%");
},
uploadProgress: function(event, position, total, percentComplete) {
$("#bar").width(percentComplete+'%');
$("#yuzde").html(percentComplete+'%');
},
success: function(){
$("#bar").width('100%');
$("#yuzde").html('100%');
},
complete: function(response){
alert(response.responseText); //sunucudan gelen cevap iceriği
$("#mesaj").html("<font color='green'>Dosya başarılı bir şekilde yüklendi</font>");
},
error: function(){
$("#mesaj").html("<font color='red'> Bir hata oluştu</font>");
}
});
});
Browser Desteğini Kontrol Etmek
//check whether client browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob){
}
else {
//Error for older unsupported browsers that doesn't support HTML5 File API
alert("Please upgrade your browser, because your current browser lacks some new features we need!");
}
}
Dosya Boyutunu Kontrol Edip Dosyayı Göndermek
//check whether client browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob){
var fsize = $('#FileInput')[0].files[0].size; //get file size
var ftype = $('#FileInput')[0].files[0].type; // get file type
//allow file types
switch(ftype){
case 'image/png':
case 'image/gif':
case 'image/jpeg':
case 'image/pjpeg':
case 'text/plain':
case 'text/html':
case 'application/x-zip-compressed':
case 'application/pdf':
case 'application/msword':
case 'application/vnd.ms-excel':
case 'video/mp4':
break;
default:
$("#output").html("<b>"+ftype+"</b> Unsupported file type!");
return false
}
//Allowed file size is less than 5 MB (1048576 = 1 mb)
if(fsize>5242880){
alert("<b>"+fsize +"</b> Too big file! <br />File is too big, it should be less than 5 MB.");
return false
}
}
else{
//Error for older unsupported browsers that doesn't support HTML5 File API
alert("Please upgrade your browser, because your current browser lacks some new features we need!");
return false
}
}
Progress Bar
//Progress bar
$('#progressbox').show();
$('#progressbar').width(percentComplete + '%') //update progressbar percent complete
$('#statustxt').html(percentComplete + '%'); //update status text
if(percentComplete>50){
$('#statustxt').css('color','#000'); //change status text to white after 50%
}
}
Parametreli Kullanım
var options = {
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
};
// pass options to ajaxForm
$('#myForm').ajaxForm(options);
Parametreler:
beforeSerialize
Callback function to be invoked before the form is serialized. This provides an opportunity to manipulate the form before it's values are retrieved. The beforeSerialize
function is invoked with two arguments: the jQuery object for the form, and the Options Object passed into ajaxForm/ajaxSubmit.
beforeSerialize: function($form, options) {
// return false to cancel submit
}
Default value: null
beforeSubmit
Callback function to be invoked before the form is submitted. The 'beforeSubmit' callback can be provided as a hook for running pre-submit logic or for validating the form data. If the 'beforeSubmit' callback returns false then the form will not be submitted. The 'beforeSubmit' callback is invoked with three arguments: the form data in array format, the jQuery object for the form, and the Options Object passed into ajaxForm/ajaxSubmit.
beforeSubmit: function(arr, $form, options) {
// The array of form data takes the following form:
// [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
// return false to cancel submit
}
Default value: null
clearForm
Boolean flag indicating whether the form should be cleared if the submit is successful
Default value: null
data
An object containing extra data that should be submitted along with the form.
data: { key1: 'value1', key2: 'value2' }
dataType
Expected data type of the response. One of: null, 'xml', 'script', or 'json'. The dataType
option provides a means for specifying how the server response should be handled. This maps directly to the jQuery.httpData
method. The following values are supported:
'xml': if dataType == 'xml' the server response is treated as XML and the 'success' callback method, if specified, will be passed the responseXML value
'json': if dataType == 'json' the server response will be evaluted and passed to the 'success' callback, if specified
'script': if dataType == 'script' the server response is evaluated in the global context
Default value: null
error
Callback function to be invoked upon error.
forceSync
Boolean value. Set to true to remove short delay before posting form when uploading files (or using the iframe option). The delay is used to allow the browser to render DOM updates prior to performing a native form submit. This improves usability when displaying notifications to the user, such as "Please Wait..."
Default value: false
iframe
Boolean flag indicating whether the form should always target the server response to an iframe. This is useful in conjuction with file uploads. See the File Uploads documentation on the Code Samples page for more info.
Default value: false
iframeSrc
String value that should be used for the iframe's src attribute when/if an iframe is used.
Default value: about:blank
Default value for pages that use https
protocol: javascript:false
iframeTarget
Identifies the iframe element to be used as the response target for file uploads. By default, the plugin will create a temporary iframe element to capture the response when uploading files. This options allows you to use an existing iframe if you wish. When using this option the plugin will make no attempt at handling the response from the server.
Default value: null
replaceTarget
Optionally used along with the the target
option. Set to true
if the target should be replaced or false
if only the target contents should be replaced.
Default value: false
resetForm
Boolean flag indicating whether the form should be reset if the submit is successful
Default value: null
semantic
Boolean flag indicating whether data must be submitted in strict semantic order (slower). Note that the normal form serialization is done in semantic order with the exception of input elements of type="image"
. You should only set the semantic option to true if your server has strict semantic requirements and your form contains an input element of type="image"
.
Default value: false
success
Callback function to be invoked after the form has been submitted. If a 'success' callback function is provided it is invoked after the response has been returned from the server. It is passed the following arguments:
- 1.) responseText or responseXML value (depending on the value of the dataType option).
- 2.) statusText
- 3.) xhr (or the jQuery-wrapped form element if using jQuery < 1.4)
- 4.) jQuery-wrapped form element (or undefined if using jQuery < 1.4)
Default value: null
target
Identifies the element(s) in the page to be updated with the server response. This value may be specified as a jQuery selection string, a jQuery object, or a DOM element.
Default value: null
type
The method in which the form data should be submitted, 'GET' or 'POST'.
Default value: value of form's method
attribute (or 'GET' if none found)
uploadProgress
Callback function to be invoked with upload progress information (if supported by the browser). The callback is passed the following arguments:
- 1.) event; the browser event
- 2.) position (integer)
- 3.) total (integer)
- 4.) percentComplete (integer)
Default value: null
url
URL to which the form data will be submitted.
Default value: value of form's action
attribute
Parametreli Örnek
target: '#mesaj', //sunucu mesaji
//url: 'comment.php',
//beforeSubmit: showRequest, // pre-submit callback
uploadProgress: function (event, position, total, percentComplete) {
$("#progress1 .progress-bar").css('width', percentComplete + '%');
$("#progress1 .progress-bar").html(percentComplete + '%');
},
success: function () {
//alert('Thanks for your comment!');
},
error: function () {
$("#mesaj").html("<font color='red'> Bir hata oluştu</font>");
},
complete: function (response) {
//$("#mesaj").html("<font color='green'>Dosya başarılı bir şekilde yüklendi</font>");
},
//url: url, // override for form's 'action' attribute
//type: type, // 'get' or 'post', override for form's 'method' attribute
//dataType: null, // 'xml', 'script', or 'json' (expected server response type)
clearForm: true, // clear all form fields after successful submit
resetForm: true, // reset the form after successful submit
//timeout: 3000 // $.ajax options can be used here too, for example:
};
$('#resim_yukle').ajaxForm(options);
Tamamlanmış Sonuç Kodları
<head>
<meta charset="utf-8">
<title>PHP Upload jQuery Progress</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
#progress { display: none; position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#yuzde { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<form id="dosyayukle" action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="dosya">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="yuzde">0%</div >
</div>
<div id="mesaj"></div>
<script>
$(document).ready(function()
{
$("#dosyayukle").ajaxForm({
beforeSend: function(){
$("#progress").show();
//herşeyi temizliyoruz.
$("#bar").width('0%');
$("#mesaj").html("");
$("#yuzde").html("0%");
},
uploadProgress: function(olay, yuklenen, toplam, yuzde){
$("#bar").width(yuzde+'%');
$("#yuzde").html(yuzde+'%');
},
success: function(){
$("#bar").width('100%');
$("#yuzde").html('100%');
},
complete: function(response){
$("#mesaj").html("<font color='green'>Dosya başarılı bir şekilde yüklendi</font>");
},
error: function(){
$("#mesaj").html("<font color='red'> Bir hata oluştu</font>");
}
});
});
</script>
</body>
</html>
Sunucu Tarafındaki PHP Kodu
if(isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"]== UPLOAD_ERR_OK)
{
############ Edit settings ##############
$UploadDirectory = '/home/website/file_upload/uploads/'; //specify upload directory ends with / (slash)
##########################################
/*
Note : You will run into errors or blank page if "memory_limit" or "upload_max_filesize" is set to low in "php.ini".
Open "php.ini" file, and search for "memory_limit" or "upload_max_filesize" limit
and set them adequately, also check "post_max_size".
*/
//check if this is an ajax request
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
die();
}
//Is file size is less than allowed size.
if ($_FILES["FileInput"]["size"] > 5242880) {
die("File size is too big!");
}
//allowed file type Server side check
switch(strtolower($_FILES['FileInput']['type']))
{
//allowed file types
case 'image/png':
case 'image/gif':
case 'image/jpeg':
case 'image/pjpeg':
case 'text/plain':
case 'text/html': //html file
case 'application/x-zip-compressed':
case 'application/pdf':
case 'application/msword':
case 'application/vnd.ms-excel':
case 'video/mp4':
break;
default:
die('Unsupported File!'); //output error
}
$File_Name = strtolower($_FILES['FileInput']['name']);
$File_Ext = substr($File_Name, strrpos($File_Name, '.')); //get file extention
$Random_Number = rand(0, 9999999999); //Random number to be added to name.
$NewFileName = $Random_Number.$File_Ext; //new file name
if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName ))
{
// do other stuff
die('Success! File Uploaded.');
}else{
die('error uploading File!');
}
}
else
{
die('Something wrong with upload! Is "upload_max_filesize" set correctly?');
}
Kaynaklar