首页 > 语言 > PHP > 正文

二款php ajax文件上传代码

2024-09-04 11:45:04
字体:大 中 小
来源:转载
供稿:网友

这两款ajax文件上传代码其实都是利用了js的iframe或ajax post来实现的下面来看看代码吧,代码如下:

  1. <html>  
  2. <body>  
  3. <h1>ajax file upload sample</h1><br/><input id="uplaod" name="btn_send" type="button" value="上传测试"/>  
  4. <div id=result></div>  
  5. <pre class=js name="code"> 
  6. <script language="javascript">  
  7. // 上传函数  
  8. function btn_send.onclick() {  
  9. data = ""  
  10. spliter = "-------7d8d733180846"  
  11. datadatadata = data + spliter + " "  
  12. datadatadata = data + "content-disposition: form-data; name="photofile"; filename="c:/a.txt" "  
  13. // datadatadata = data + "content-type: image/pjpeg" + vbcrlf  
  14. datadatadata = data + "content-type: text/plain" + " " + " "  
  15. text = "my name is wilson lin."  
  16. postlength = text.length + data.length + 2 + spliter.length + 4  
  17. package = data + text + " " + spliter + "-- " 
  18.  
  19. alert(package)  
  20. // 把xml文档发送到web服务器  
  21. var xmlhttp = new activexobject("microsoft.xmlhttp");  
  22. xmlhttp.open("post","./upload.php",false);  
  23. xmlhttp.setrequestheader("content-type", "multipart/form-data; boundary=-----7d8d733180846");  
  24. xmlhttp.setrequestheader("content-length", postlength);  
  25. xmlhttp.send(package);  
  26. // 显示服务器返回的信息  
  27. result.innerhtml=xmlhttp.responsetext;  
  28. }  
  29. </script>  
  30. </pre>  
  31. </body>  
  32. </html> 
  33.  
  34.  
  35. <html> 
  36. <script language="javascript"> 
  37. <!-- 
  38.    var xmlhttp; 
  39.   function createxmlhttprequest() { 
  40.    if (window.activexobject) { 
  41.     xmlhttp = new activexobject("microsoft.xmlhttp"); 
  42.    } 
  43.    else if (window.xmlhttprequest) { 
  44.     xmlhttp = new xmlhttprequest(); 
  45.    } 
  46.   } 
  47.   function uploade(e){ 
  48.    var fileadd 
  49.    fileadd = e; 
  50.     
  51.     createxmlhttprequest(); 
  52.     xmlhttp.onreadystatechange = handlestatechange; 
  53.     var url = "pic_upload.asp教程?add="+fileadd+"&timestamp="+new date().gettime(); 
  54.     xmlhttp.open("get",url,true); 
  55.     xmlhttp.send(null); 
  56.    
  57.   } 
  58.   function handlestatechange() { 
  59.    document.getelementbyid("content").innerhtml = "这里写进度条"; 
  60.    if (xmlhttp.readystate == 4) { 
  61.     if (xmlhttp.status == 200) { 
  62.       
  63.      document.getelementbyid("content").innerhtml = xmlhttp.responsetext; 
  64.        
  65.     } 
  66.     else{ 
  67.      //alert(xmlhttp.status); 
  68.                                                                                   alert('错误,请联系管理员!'); 
  69.       
  70.     } 
  71.    } 
  72.   } 
  73. //--> 
  74. </script> 
  75.  <body> 
  76. <input type=file name="mefile" id="fileadd" onchange="alert(document.getelementbyid('fileadd').value);"> 
  77. <input type="submit" value="上传" onclick="uploade(document.getelementbyid('fileadd').value);"> 
  78. <div id="content"></div> 
  79.  </body> 
  80. </html> 

upload.php文件,代码如下:

  1. <?php  
  2. // $_files['photofile']:是获得上传图片的数组  
  3. // $uploadfile:存放地址  
  4. $uploadfile = "./".$_files['photofile']['name'];  
  5. copy( $_files['photofile']['tmp_name'], $uploadfile );  
  6. echo "url: <a href='http://localhost/".$_files['photofile']['name']."' target='_blank'>".$_files['photofile']['name']."</a><br/>";  
  7. ?>  
  8. upload successed! 

实例代码二,代码如下:

  1. <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> 
  2. <html xmlns="http://www.w3.org/1999/xhtml"> 
  3. <head> 
  4. <meta http-equiv="content-type" content="text/html; charset=gb2312" /> 
  5. <title>无刷新文件上传系统</title> 
  6. </head> 
  7. <body> 
  8. <style> 
  9. .fu_list { 
  10.  width:600px; 
  11.  background:#ebebeb; 
  12.  font-size:12px; 
  13. } 
  14. .fu_list td { 
  15.  padding:5px; 
  16.  line-height:20px; 
  17.  background-color:#fff; 
  18. } 
  19. .fu_list table { 
  20.  width:100%; 
  21.  border:1px solid #ebebeb; 
  22. } 
  23. .fu_list thead td { 
  24.  background-color:#f4f4f4; 
  25. } 
  26. .fu_list b { 
  27.  font-size:14px; 
  28. } 
  29. /*file容器样式*/ 
  30. a.files { 
  31.  width:90px; 
  32.  height:30px; 
  33.  overflow:hidden; 
  34.  display:block; 
  35.  border:1px solid #bebebe; 
  36.  background:url(img/fu_btn.gif) left top no-repeat; 
  37.  text-decoration:none; 
  38. } 
  39. a.files:hover { 
  40.  background-color:#ffffee; 
  41.  background-position:0 -30px; 
  42. } 
  43. /*file设为透明,并覆盖整个触发面*/ 
  44. a.files input { 
  45.  margin-left:-350px; 
  46.  font-size:30px; 
  47.  cursor:pointer; 
  48.  filter:alpha(opacity=0); 
  49.  opacity:0; 
  50. } 
  51. /*取消点击时的虚线框*/ 
  52. a.files, a.files input { 
  53.  outline:none;/*ff*/ 
  54.  hide-focus:expression(this.hidefocus=true);/*ie*/ 
  55. } 
  56. </style> 
  57. <form id="uploadform" action="file.php"> 
  58.   <table width="63%" border="0" cellspacing="1" class="fu_list"> 
  59.     <thead> 
  60.       <tr> 
  61.         <td colspan="2"><b>上传文件</b></td> 
  62.       </tr> 
  63.     </thead> 
  64.     <tbody> 
  65.       <tr> 
  66.         <td align="right" width="15%" style="line-height:35px;">添加文件:</td> 
  67.         <td><a href="javascript:void(0);" class="files" id="idfile"></a> <img id="idprocess" style="display:none;" src="img/loading.gif" /></td> 
  68.       </tr> 
  69.       <tr> 
  70.         <td colspan="2"><table border="0" cellspacing="0"> 
  71.             <thead> 
  72.               <tr> 
  73.                 <td>文件路径</td> 
  74.                 <td width="100"></td> 
  75.               </tr> 
  76.             </thead> 
  77.             <tbody id="idfilelist"> 
  78.             </tbody> 
  79.           </table></td> 
  80.       </tr> 
  81.       <tr> 
  82.         <td colspan="2" style="color:gray"><label for="textfield"></label> 
  83.         <input type="text" name="uploadsfile" id="uploadsfile" /></td> 
  84.       </tr> 
  85.       <tr> 
  86.         <td colspan="2" style="color:gray">温馨提示:最多可同时上传 <b id="idlimit"></b> 个文件,只允许上传 <b id="idext"></b> 文件。 </td> 
  87.       </tr> 
  88.       <tr> 
  89.         <td colspan="2" align="center" id="idmsg"><input type="button" value="开始上传" id="idbtnupload" disabled="disabled" /> 
  90.           &nbsp;&nbsp;&nbsp; 
  91.           <input type="button" value="全部取消" id="idbtndel" disabled="disabled" /> 
  92.         </td> 
  93.       </tr> 
  94.     </tbody> 
  95.   </table> 
  96. </form> 
  97. <script type="text/javascript"> 
  98.  
  99. var isie = (document.all) ? true : false; 
  100.  
  101. var $ = function (id) { 
  102.     return "string" == typeof id ? document.getelementbyid(id) : id; 
  103. }; 
  104.  
  105. var class = { 
  106.   create: function() { 
  107.     return function() { 
  108.       this.initialize.apply(this, arguments); 
  109.     } 
  110.   } 
  111. } 
  112.  
  113. var extend = function(destination, source) { 
  114.  for (var property in source) { 
  115.   destination[property] = source[property]; 
  116.  } 
  117. } 
  118.  
  119. var bind = function(object, fun) { 
  120.  return function() { 
  121.   return fun.apply(object, arguments); 
  122.  } 
  123. } 
  124.  
  125. var each = function(list, fun){ 
  126.  for (var i = 0, len = list.length; i < len; i++) { fun(list[i], i); } 
  127. }; 
  128.  
  129. //文件上传类 
  130. var fileupload = class.create(); 
  131. fileupload.prototype = { 
  132.   //表单对象,文件控件存放空间 
  133.   initialize: function(form, folder, options) { 
  134.  
  135.  this.form = $(form);//表单 
  136.  this.folder = $(folder);//文件控件存放空间 
  137.  this.files = [];//文件集合 
  138.  
  139.  this.setoptions(options); 
  140.  
  141.  this.filename = this.options.filename; 
  142.  this._framename = this.options.framename; 
  143.  this.limit = this.options.limit; 
  144.  this.distinct = !!this.options.distinct; 
  145.  this.extin = this.options.extin; 
  146.  this.extout = this.options.extout; 
  147.  
  148.  this.oninifile = this.options.oninifile; 
  149.  this.onempty = this.options.onempty; 
  150.  this.onnotextin = this.options.onnotextin; 
  151.  this.onextout = this.options.onextout; 
  152.  this.onlimite = this.options.onlimite; 
  153.  this.onsame = this.options.onsame; 
  154.  this.onfail = this.options.onfail; 
  155.  this.onini = this.options.onini; 
  156.  
  157.  if(!this._framename){ 
  158.   //为每个实例创建不同的iframe 
  159.   this._framename = "uploadframe_" + math.floor(math.random() * 1000); 
  160.   //ie不能修改iframe的name 
  161.   var oframe = isie ? document.createelement("<iframe name="" + this._framename + "">") : document.createelement("iframe"); 
  162.   //为ff设置name 
  163.   oframe.name = this._framename; 
  164.   oframe.style.display = "none"; 
  165.   //在ie文档未加载完用appendchild会报错 
  166.   document.body.insertbefore(oframe, document.body.childnodes[0]); 
  167.  }//开源代码Vevb.com 
  168.  
  169.  //设置form属性,关键是target要指向iframe 
  170.  this.form.target = this._framename; 
  171.  this.form.method = "post"; 
  172.  //注意ie的form没有enctype属性,要用encoding 
  173.  this.form.encoding = "multipart/form-data"; 
  174.  
  175.  //整理一次 
  176.  this.ini(); 
  177.   }, 
  178.   //设置默认属性 
  179.   setoptions: function(options) { 
  180.     this.options = {//默认值 
  181.   filename: "files[]",//文件上传控件的name,配合后台使用 
  182.   framename: "",//iframe的name,要自定义iframe的话这里设置name 
  183.   oninifile: function(){},//整理文件时执行(其中参数是file对象) 
  184.   onempty: function(){},//文件空值时执行 
  185.   limit:  10,//文件数限制,0为不限制 
  186.   onlimite: function(){},//超过文件数限制时执行 
  187.   distinct: true,//是否不允许相同文件 
  188.   onsame:  function(){},//有相同文件时执行 
  189.   extin:  ["gif","jpg","rar","zip","iso","swf","exe"],//允许后缀名 
  190.   onnotextin: function(){},//不是允许后缀名时执行 
  191.   extout:  [],//禁止后缀名,当设置了extin则extout无效 
  192.   onextout: function(){},//是禁止后缀名时执行 
  193.   onfail:  function(){},//文件不通过检测时执行(其中参数是file对象) 
  194.   onini:  function(){}//重置时执行 
  195.     }; 
  196.     extend(this.options, options || {}); 
  197.   }, 
  198.   //整理空间 
  199.   ini: function() { 
  200.  //整理文件集合 
  201.  this.files = []; 
  202.  //整理文件空间,把有值的file放入文件集合 
  203.  each(this.folder.getelementsbytagname("input"), bind(this, function(o){ 
  204.   if(o.type == "file"){ o.value && this.files.push(o); this.oninifile(o); } 
  205.  })) 
  206.  //插入一个新的file 
  207.  var file = document.createelement("input"); 
  208.  file.name = this.filename; file.type = "file"; file.onchange = bind(this, function(){ this.check(file); this.ini(); }); 
  209.  this.folder.appendchild(file); 
  210.  //执行附加程序 
  211.  this.onini(); 
  212.   }, 
  213.   //检测file对象 
  214.   check: function(file) { 
  215.  //检测变量 
  216.  var bcheck = true; 
  217.  //空值、文件数限制、后缀名、相同文件检测 
  218.  if(!file.value){ 
  219.   bcheck = false; this.onempty(); 
  220.  } else if(this.limit && this.files.length >= this.limit){ 
  221.   bcheck = false; this.onlimite(); 
  222.  } else if(!!this.extin.length && !regexp(".(" + this.extin.join("|") + ")$", "i").test(file.value)){ 
  223.   //检测是否允许后缀名 
  224.   bcheck = false; this.onnotextin(); 
  225.  } else if(!!this.extout.length && regexp(".(" + this.extout.join("|") + ")$", "i").test(file.value)) { 
  226.   //检测是否禁止后缀名 
  227.   bcheck = false; this.onextout(); 
  228.  } else if(!!this.distinct) { 
  229.   each(this.files, function(o){ if(o.value == file.value){ bcheck = false; } }) 
  230.   if(!bcheck){ this.onsame(); } 
  231.  } 
  232.  //没有通过检测 
  233.  !bcheck && this.onfail(file); 
  234.   }, 
  235.   //删除指定file 
  236.   delete: function(file) { 
  237.  //移除指定file 
  238.  this.folder.removechild(file); this.ini(); 
  239.   }, 
  240.   //删除全部file 
  241.   clear: function() { 
  242.  //清空文件空间 
  243.  each(this.files, bind(this, function(o){ this.folder.removechild(o); })); this.ini(); 
  244.   } 
  245. } 
  246.  
  247. var fu = new fileupload("uploadform", "idfile", { extin: ["gif","jpg"], 
  248.  oninifile: function(file){ file.value ? file.style.display = "none" : this.folder.removechild(file); }, 
  249.  onempty: function(){ alert("请选择一个文件"); }, 
  250.  onlimite: function(){ alert("超过上传限制"); }, 
  251.  onsame: function(){ alert("已经有相同文件"); }, 
  252.  onnotextin: function(){ alert("只允许上传" + this.extin.join(",") + "文件"); }, 
  253.  onfail: function(file){ this.folder.removechild(file); }, 
  254.  onini: function(){ 
  255.   //显示文件列表 
  256.   var arrrows = []; 
  257.   if(this.files.length){ 
  258.    var othis = this; 
  259.    each(this.files, function(o){ 
  260.     var a = document.createelement("a"); a.innerhtml = "取消"; a.href = "javascript:void(0);"; 
  261.     a.onclick = function(){ othis.delete(o); return false; }; 
  262.     arrrows.push([o.value, a]); 
  263.    }); 
  264.   } else { arrrows.push(["<font color='gray'>没有添加文件</font>", "&nbsp;"]); } 
  265.   addlist(arrrows); 
  266.   //设置按钮 
  267.   $("idbtnupload").disabled = $("idbtndel").disabled = this.files.length <= 0; 
  268.  } 
  269. }); 
  270.  
  271. $("idbtnupload").onclick = function(){ 
  272.  //显示文件列表 
  273.  var arrrows = []; 
  274.  each(fu.files, function(o){ arrrows.push([o.value, "&nbsp;"]); }); 
  275.  addlist(arrrows); 
  276.  
  277.  fu.folder.style.display = "none"; 
  278.  $("idprocess").style.display = ""; 
  279.  $("idmsg").innerhtml = "正在添加文件到您的网盘中,请稍候……<br />有可能因为网络问题,出现程序长时间无响应,请点击"<a href='?'><font color='red'>取消</font></a>"重新上传文件"; 
  280.  
  281.  fu.form.submit(); 
  282. } 
  283.  
  284. //用来添加文件列表的函数 
  285. function addlist(rows){ 
  286.  //根据数组来添加列表 
  287.  var filelist = $("idfilelist"), ofragment = document.createdocumentfragment(); 
  288.  //用文档碎片保存列表 
  289.  each(rows, function(cells){ 
  290.   var row = document.createelement("tr"); 
  291.   each(cells, function(o){ 
  292.    var cell = document.createelement("td"); 
  293.    if(typeof o == "string"){ cell.innerhtml = o; }else{ cell.appendchild(o); } 
  294.    row.appendchild(cell); 
  295.   }); 
  296.   ofragment.appendchild(row); 
  297.  }) 
  298.  //ie的table不支持innerhtml所以这样清空table 
  299.  while(filelist.haschildnodes()){ filelist.removechild(filelist.firstchild); } 
  300.  filelist.appendchild(ofragment); 
  301. } 
  302.  
  303.  
  304. $("idlimit").innerhtml = fu.limit; 
  305.  
  306. $("idext").innerhtml = fu.extin.join(","); 
  307.  
  308. $("idbtndel").onclick = function(){ fu.clear(); } 
  309.  
  310. //在后台通过window.parent来访问主页面的函数 
  311. function finish(msg) 
  312. {  
  313.  $('uploadsfile').value=msg;  
  314. } 
  315.  
  316. </script> 
  317. </body> 
  318. </html> 

php接ajax上传代码,代码如下:

  1. <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> 
  2. <html xmlns="http://www.w3.org/1999/xhtml"> 
  3. <head> 
  4. <meta http-equiv="content-type" content="text/html; charset=gb2312" /> 
  5. <title>无标题文档</title> 
  6. </head> 
  7. <body> 
  8. <? 
  9. $sort=12; 
  10. $f_type=strtolower("swf,jpg,rar,zip,7z,iso,gif");//设置可上传的文件类型  
  11. $file_size_max=200*1024*1024;//限制单个文件上传最大容量  
  12. $overwrite = 0;//是否允许覆盖相同文件,1:允许,0:不允许  
  13. $f_input="files";//设置上传域名称 
  14.     foreach($_files[$f_input]["error"] as $key => $error){  
  15.         $up_error="no";  
  16.         if ($error == upload_err_ok){  
  17.             $f_name=$_files[$f_input]['name'][$key];//获取上传源文件名  
  18.     
  19.             $uploadfile=$uploaddir.strtolower(basename($f_name));  
  20.               
  21.             $tmp_type=substr(strrchr($f_name,"."),1);//获取文件扩展名 
  22.    $tmp_type=strtolower($tmp_type);  
  23.             if(!stristr($f_type,$tmp_type)){  
  24.                 echo "<script>alert('对不起,不能上传".$tmp_type."格式文件, ".$f_name." 文件上传失败!')</script>";  
  25.                 $up_error="yes";  
  26.             }  
  27.               
  28.             if ($_files[$f_input]['size'][$key]>$file_size_max) {  
  29.     
  30.                 echo "<script>alert('对不起,你上传的文件 ".$f_name." 容量为".round($_files[$f_input] 
  31. ['size'][$key]/1024)."kb,大于规定的".($file_size_max/1024)."kb,上传失败!')</script>";  
  32.                 $up_error="yes";  
  33.             }  
  34.               
  35.             if (file_exists($uploadfile)&&!$overwrite){  
  36.                 echo "<script>alert('对不起,文件 ".$f_name." 已经存在,上传失败!')</script>";  
  37.                 $up_error="yes";  
  38.             }  
  39.              $string = 'abcdefghijklmnopgrstuvwxyz0123456789'; 
  40. $rand = ''; 
  41. for ($x=0;$x<12;$x++) 
  42.   $rand .= substr($string,mt_rand(0,strlen($string)-1),1); 
  43. $t=date("ymdhis").substr($gettime[0],2,6).$rand; 
  44. $attdir="./file/";   
  45.     if(!is_dir($attdir))    
  46.     {  mkdir($attdir);} 
  47.             $uploadfile=$attdir.$t.".".$tmp_type;  
  48.             if(($up_error!="yes") and (move_uploaded_file($_files[$f_input]['tmp_name'] 
  49.  
  50. [$key], $uploadfile))){ 
  51.  
  52.                   
  53.     $_msg=$_msg.$f_name.'上传成功 '; 
  54.      
  55.      
  56.             }  
  57.    else{ 
  58.    $_msg=$_msg.$f_name.'上传失败 '; 
  59.    } 
  60.         }  
  61.  
  62.     }  
  63. echo "<script>window.parent.finish('".$_msg."');</script>";  
  64. ?> 
  65. </body> 
  66. </html> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表