項目需求:1.PHP+Ajax無刷新帶進度條圖片上傳,2.帶進度條。所需插件:jquery.js,jquery.form.js。
最近在做一個手機web項目,需要用到Ajax上傳功圖片能,項目要求PHP無刷新上傳圖片,并且要帶進度條,下面就來講一下我的實現方法,先看效果圖

本示例需要使用的是jquery.js,jquery.form.js,demo里面包含有,你可以在文章下方進行下載。
第一步,建立前端頁面index.html
此段是前端展示內容,這里需要說明的是由于input:file標簽顯示不太美觀,所以我把它隱藏了。而使用一個a標簽.uploadbtn來調用file標簽的click事件,用來打開并選擇文件。
注意:文件上傳時form的屬性enctype必須設置為:multipart/form-data
charset="UTF-8">
php-ajax無刷新上傳(帶進度條)demo
name="description" content="" />
name="viewport" content="width=device-width , initial-scale=1.0 , user-scalable=0 , minimum-scale=1.0 , maximum-scale=1.0" />
type='text/javascript' src='js/jquery-2.0.3.min.js'>
type='text/javascript' src='js/jquery.form.js'>
href="css/style.css" rel="external nofollow" type="text/css" rel="stylesheet"/>
style="width:500px;margin:10px auto; border:solid 1px #ddd; overflow:hidden; ">
id='myupload' action='upload.php' method='post' enctype='multipart/form-data'>
type="file" id="uploadphoto" name="uploadfile" value="請點擊上傳圖片" style="display:none;" />
class="imglist">
class="res">
class="progress">
class="progress-bar progress-bar-striped"> class="percent">50%
href="javascript:void(0);" rel="external nofollow" onclick="uploadphoto.click()" class="uploadbtn">點擊上傳文件
第二步,Ajax提交部分
這部份就是Ajax的提交部份,過程如下:
在提交開始通過beforeSend回調函數設置進度條顯示出來,進度條寬度為0%,進度值0%;
在上傳過程中通過uploadProgress回調函數實時返回的數據,更改進度條的寬度和進度值。
在上傳成功后,通過success回調函數輸出上傳為數據信息(圖片名稱,大小,地址等)并把圖片輸出到頁面上預覽。
當然如果失敗,有error回調函數幫你進行高度。
type="text/javascript">
$(document).ready(function(e) {
var progress = $(".progress");
var progress_bar = $(".progress-bar");
var percent = $('.percent');
$("#uploadphoto").change(function(){
$("#myupload").ajaxSubmit({
dataType: 'json', //數據格式為json
beforeSend: function() { //開始上傳
progress.show();
var percentVal = '0%';
progress_bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%'; //獲得進度
progress_bar.width(percentVal); //上傳進度條寬度變寬
percent.html(percentVal); //顯示上傳進度百分比
},
success: function(data) {
if(data.status == 1){
var src = data.url;
var attstr= '+src+'">';
$(".imglist").append(attstr);
$(".res").html("上傳圖片"+data.name+"成功,圖片大小:"+data.size+"K,文件地址:"+data.url);
}else{
$(".res").html(data.content);
}
progress.hide();
},
error:function(xhr){ //上傳失敗
alert("上傳失敗");
progress.hide();
}
});
});
});
第三步,后端PHP代碼upload.php
后端處理代碼,就是PHP文件上傳,不過上傳的時候需要做一些判斷,如文件格式、文件大小等。
注意:我上面ajax返回格式是json,所以在圖片json代碼是一定要正確規范,否則會出現上傳不成功的提示。
$picname = $_FILES['uploadfile']['name'];
$picsize = $_FILES['uploadfile']['size'];
if ($picname != "") {
if ($picsize > 2014000) { //限制上傳大小
echo '{"status":0,"content":"圖片大小不能超過2M"}';
exit;
}
$type = strstr($picname, '.'); //限制上傳格式
if ($type != ".gif" && $type != ".jpg?www.myhack58.com" && $type != "png?www.myhack58.com") {
echo '{"status":2,"content":"圖片格式不對!"}';
exit;
}
$rand = rand(100, 999);
$pics = uniqid() . $type; //命名圖片名稱
//上傳路徑
$pic_path = "images/". $pics;
|