在php文件上傳這一款,如果不用ajax來實現,效果都不怎麼樣,用戶體驗不怎麼好,下面我們就來看看這一款ajax+php 無刷新文件上傳代碼吧。ajax+php 無刷新文件上傳代碼
ajax+php教程 無刷新文件上傳代碼
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.bKjia.c0m/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>ajax+php 無刷新文件上傳代碼</title>
</head>
<body>
<style>
.fu_list {
width:600px;
background:#ebebeb;
font-size:12px;
}
.fu_list td {
padding:5px;
line-height:20px;
background-color:#fff;
}
.fu_list table {
width:100%;
border:1px solid #ebebeb;
}
.fu_list thead td {
background-color:#f4f4f4;
}
.fu_list b {
font-size:14px;
}
/*file容器樣式*/
a.files {
width:90px;
height:30px;
overflow:hidden;
display:block;
border:1px solid #bebebe;
background:url(img/fu_btn.gif) left top no-repeat;
text-decoration:none;
}
a.files:hover {
background-color:#ffffee;
background-position:0 -30px;
}
/*file設為透明,並覆蓋整個觸發面*/
a.files input {
margin-left:-350px;
font-size:30px;
cursor:pointer;
filter:alpha(opacity=0);
opacity:0;
}
/*取消點擊時的虛線框*/
a.files, a.files input {
outline:none;/*ff*/
hide-focus:expression(this.hidefocus=true);/*ie*/
}
</style>
<form id="uploadform" action="file.php">
<table border="0" cellspacing="1" class="fu_list">
<thead>
<tr>
<td colspan="2"><b>上傳文件</b></td>
</tr>
</thead>
<tbody>
<tr>
<td align="right" width="15%" style="line-height:35px;">添加文件:</td>
<td><a href="網頁特效:void(0);" class="files" id="idfile"></a> <img id="idprocess" style="display:none;" src="img/loading.gif" /></td>
</tr>
<tr>
<td colspan="2"><table border="0" cellspacing="0">
<thead>
<tr>
<td>文件路徑</td>
<td width="100"></td>
</tr>
</thead>
<tbody id="idfilelist">
</tbody>
</table></td>
</tr>
<tr>
<td colspan="2" style="color:gray">溫馨提示:最多可同時上傳 <b id="idlimit"></b> 個文件,只允許上傳 <b id="idext"></b> 文件。 </td>
</tr>
<tr>
<td colspan="2" align="center" id="idmsg"><input type="button" value="開始上傳" id="idbtnupload" disabled="disabled" />
<input type="button" value="全部取消" id="idbtndel" disabled="disabled" />
</td>
</tr>
</tbody>
</table>
</form>
<script type="text/網頁特效">
var isie = (document.all) ? true : false;
var $ = function (id) {
return "string" == typeof id ? document.getelementbyid(id) : id;
};
var class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
var extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
}
var bind = function(object, fun) {
return function() {
return fun.apply(object, arguments);
}
}
var each = function(list, fun){
for (var i = 0, len = list.length; i < len; i++) { fun(list[i], i); }
};
//文件上傳類
var fileupload = class.create();
fileupload.prototype = {
//表單對象,文件控件存放空間
initialize: function(form, folder, options) {
this.form = $(form);//表單
this.folder = $(folder);//文件控件存放空間
this.files = [];//文件集合
this.setoptions(options);
this.filename = this.options.filename;
this._framename = this.options.framename;
this.limit = this.options.limit;
this.distinct = !!this.options.distinct;
this.extin = this.options.extin;
this.extout = this.options.extout;
this.oninifile = this.options.oninifile;
this.onempty = this.options.onempty;
this.onnotextin = this.options.onnotextin;
this.onextout = this.options.onextout;
this.onlimite = this.options.onlimite;
this.onsame = this.options.onsame;
this.onfail = this.options.onfail;
this.onini = this.options.onini;
if(!this._framename){
//為每個實例創建不同的iframe
this._framename = "uploadframe_" + math.floor(math.random() * 1000);
//ie不能修改iframe的name
var oframe = isie ? document.createelement("<iframe name="" + this._framename + "">") : document.createelement("iframe");
//為ff設置name
oframe.name = this._framename;
oframe.style.display = "none";
//在ie文檔未加載完用appendchild會報錯
document.body.insertbefore(oframe, document.body.childnodes[0]);
}
//設置form屬性,關鍵是target要指向iframe
this.form.target = this._framename;
this.form.method = "post";
//注意ie的form沒有enctype屬性,要用encoding
this.form.encoding = "multipart/form-data";
//整理一次
this.ini();
},
//設置默認屬性
setoptions: function(options) {
this.options = {//默認值
filename: "files[]",//文件上傳控件的name,配合後台使用
framename: "",//iframe的name,要自定義iframe的話這裡設置name
oninifile: function(){},//整理文件時執行(其中參數是file對象)
onempty: function(){},//文件空值時執行
limit: 10,//文件數限制,0為不限制
onlimite: function(){},//超過文件數限制時執行
distinct: true,//是否不允許相同文件
onsame: function(){},//有相同文件時執行
extin: ["gif","jpg","rar","zip","iso","swf","exe"],//允許後綴名
onnotextin: function(){},//不是允許後綴名時執行
extout: [],//禁止後綴名,當設置了extin則extout無效
onextout: function(){},//是禁止後綴名時執行
onfail: function(){},//文件不通過檢測時執行(其中參數是file對象)
onini: function(){}//重置時執行
};
extend(this.options, options || {});
},
//整理空間
ini: function() {
//整理文件集合
this.files = [];
//整理文件空間,把有值的file放入文件集合
each(this.folder.getelementsbytagname("input"), bind(this, function(o){
if(o.type == "file"){ o.value && this.files.push(o); this.oninifile(o); }
}))
//插入一個新的file
var file = document.createelement("input");
file.name = this.filename; file.type = "file"; file.onchange = bind(this, function(){ this.check(file); this.ini(); });
this.folder.appendchild(file);
//執行附加程序
this.onini();
},
//檢測file對象
check: function(file) {
//檢測變量
var bcheck = true;
//空值、文件數限制、後綴名、相同文件檢測
if(!file.value){
bcheck = false; this.onempty();
} else if(this.limit && this.files.length >= this.limit){
bcheck = false; this.onlimite();
} else if(!!this.extin.length && !regexp(".(" + this.extin.join("|") + ")$", "i").test(file.value)){
//檢測是否允許後綴名
bcheck = false; this.onnotextin();
} else if(!!this.extout.length && regexp(".(" + this.extout.join("|") + ")$", "i").test(file.value)) {
//檢測是否禁止後綴名
bcheck = false; this.onextout();
} else if(!!this.distinct) {
each(this.files, function(o){ if(o.value == file.value){ bcheck = false; } })
if(!bcheck){ this.onsame(); }
}
//沒有通過檢測
!bcheck && this.onfail(file);
},
//刪除指定file
delete: function(file) {
//移除指定file
this.folder.removechild(file); this.ini();
},
//刪除全部file
clear: function() {
//清空文件空間
each(this.files, bind(this, function(o){ this.folder.removechild(o); })); this.ini();
}
}
var fu = new fileupload("uploadform", "idfile", { extin: ["gif","jpg"],
oninifile: function(file){ file.value ? file.style.display = "none" : this.folder.removechild(file); },
onempty: function(){ alert("請選擇一個文件"); },
onlimite: function(){ alert("超過上傳限制"); },
onsame: function(){ alert("已經有相同文件"); },
onnotextin: function(){ alert("只允許上傳" + this.extin.join(",") + "文件"); },
onfail: function(file){ this.folder.removechild(file); },
onini: function(){
//顯示文件列表
var arrrows = [];
if(this.files.length){
var othis = this;
each(this.files, function(o){
var a = document.createelement("a"); a.innerhtml = "取消"; a.href = "javascript:void(0);";
a.onclick = function(){ othis.delete(o); return false; };
arrrows.push([o.value, a]);
});
} else { arrrows.push(["<font color='gray'>沒有添加文件</font>", " "]); }
addlist(arrrows);
//設置按鈕
$("idbtnupload").disabled = $("idbtndel").disabled = this.files.length <= 0;
}
});
$("idbtnupload").onclick = function(){
//顯示文件列表
var arrrows = [];
each(fu.files, function(o){ arrrows.push([o.value, " "]); });
addlist(arrrows);
fu.folder.style.display = "none";
$("idprocess").style.display = "";
$("idmsg").innerhtml = "正在添加文件到您的網盤中,請稍候……<br />有可能因為網絡問題,出現程序長時間無響應,請點擊"<a href='?'><font color='red'>取消</font></a>"重新上傳文件";
fu.form.submit();
}
//用來添加文件列表的函數
function addlist(rows){
//根據數組來添加列表
var filelist = $("idfilelist"), ofragment = document.createdocumentfragment();
//用文檔碎片保存列表
each(rows, function(cells){
var row = document.createelement("tr");
each(cells, function(o){
var cell = document.createelement("td");
if(typeof o == "string"){ cell.innerhtml = o; }else{ cell.appendchild(o); }
row.appendchild(cell);
});
ofragment.appendchild(row);
})
//ie的table不支持innerhtml所以這樣清空table
while(filelist.haschildnodes()){ filelist.removechild(filelist.firstchild); }
filelist.appendchild(ofragment);
}
$("idlimit").innerhtml = fu.limit;
$("idext").innerhtml = fu.extin.join(",");
$("idbtndel").onclick = function(){ fu.clear(); }
//在後台通過window.parent來訪問主頁面的函數
function finish(msg){ alert(msg); location.href = location.href; }
</script>
</body>
</html>
file.php文件
<?
$sort=12;
$f_type=strtolower("swf,jpg,rar,zip,7z,iso,gif");//設置可上傳的文件類型
$file_size_max=200*1024*1024;//限制單個文件上傳最大容量
$overwrite = 0;//是否允許覆蓋相同文件,1:允許,0:不允許
$f_input="files";//設置上傳域名稱
foreach($_files[$f_input]["error"] as $key => $error){
$up_error="no";
if ($error == upload_err_ok){
$f_name=$_files[$f_input]['name'][$key];//獲取上傳源文件名
$uploaddir ='./www.bKjia.c0m/';
$uploadfile=$uploaddir.strtolower(basename($f_name));
$tmp_type=substr(strrchr($f_name,"."),1);//獲取文件擴展名
$tmp_type=strtolower($tmp_type);
if(!stristr($f_type,$tmp_type)){
echo "<script>alert('對不起,不能上傳".$tmp_type."格式文件, ".$f_name." 文件上傳失敗!')</script>";
$up_error="yes";
}
if ($_files[$f_input]['size'][$key]>$file_size_max) {
echo "<script>alert('對不起,你上傳的文件 ".$f_name." 容量為".round($_files[$f_input]
['size'][$key]/1024)."kb,大於規定的".($file_size_max/1024)."kb,上傳失敗!')</script>";
$up_error="yes";
}
if (file_exists($uploadfile)&&!$overwrite){
echo "<script>alert('對不起,文件 ".$f_name." 已經存在,上傳失敗!')</script>";
$up_error="yes";
}
$string = 'abcdefghijklmnopgrstuvwxyz0123456789';
$rand = '';
for ($x=0;$x<12;$x++)
$rand .= substr($string,mt_rand(0,strlen($string)-1),1);
$t=date("ymdhis").substr($gettime[0],2,6).$rand;
$attdir="./file/";
if(!is_dir($attdir))
{ mkdir($attdir);}
$uploadfile=$attdir.$t.".".$tmp_type;
if(($up_error!="yes") and (move_uploaded_file($_files[$f_input]['tmp_name']
[$key], $uploadfile))){
$_msg=$_msg.$f_name.'上傳成功n';
}
else{
$_msg=$_msg.$f_name.'上傳失敗n';
}
}
}
echo "<script>window.parent.finish('".$_msg."');</script>";
/*
在php文件上傳這一款,如果不用ajax來實現,效果都不怎麼樣,用戶體驗不怎麼好,下面我們就來看看這一款ajax+php 無刷新文件上傳代碼吧。
*/
?>