二款php ajax文件上传代码

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

  1. <html>
  2. <body>
  3. <h1>ajax file upload sample</h1><br/><input 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. alert(package)
  19. // 把xml文档发送到web服务器
  20. var xmlhttp = new activexobject("microsoft.xmlhttp");
  21. xmlhttp.open("post","./upload.php",false);
  22. xmlhttp.setrequestheader("content-type", "multipart/form-data; boundary=-----7d8d733180846");
  23. xmlhttp.setrequestheader("content-length", postlength);
  24. xmlhttp.send(package);
  25. // 显示服务器返回的信息
  26. result.innerhtml=xmlhttp.responsetext;
  27. }
  28. </script>
  29. </pre>
  30. </body>
  31. </html>
  32. <html>
  33. <script language="javascript">
  34. <!--
  35. var xmlhttp;
  36. function createxmlhttprequest() {
  37. if (window.activexobject) {
  38. xmlhttp = new activexobject("microsoft.xmlhttp");
  39. }
  40. else if (window.xmlhttprequest) {
  41. xmlhttp = new xmlhttprequest();
  42. }
  43. }
  44. function uploade(e){
  45. var fileadd
  46. fileadd = e;
  47. createxmlhttprequest();
  48. xmlhttp.onreadystatechange = handlestatechange;
  49. var url = "pic_upload.asp教程?add="+fileadd+"&timestamp="+new date().gettime();
  50. xmlhttp.open("get",url,true);
  51. xmlhttp.send(null);
  52. }
  53. function handlestatechange() {
  54. document.getelementbyid("content").innerhtml = "这里写进度条";
  55. if (xmlhttp.readystate == 4) {
  56. if (xmlhttp.status == 200) {
  57. document.getelementbyid("content").innerhtml = xmlhttp.responsetext;
  58. }
  59. else{
  60. //alert(xmlhttp.status);
  61. alert('错误,请联系管理员!');
  62. }
  63. }
  64. }
  65. //-->
  66. </script>
  67. <body>
  68. <input type=file name="mefile" onchange="alert(document.getelementbyid('fileadd').value);">
  69. <input type="submit" value="上传" onclick="uploade(document.getelementbyid('fileadd').value);">
  70. <div ></div>
  71. </body>
  72. </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 action="file.php">
  58. <table width="63%" 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%" >添加文件:</td>
  67. <td><a href="javascript:void(0);" class="files" ></a> <img src="img/loading.gif" /></td>
  68. </tr>
  69. <tr>
  70. <td colspan="2"><table cellspacing="0">
  71. <thead>
  72. <tr>
  73. <td>文件路径</td>
  74. <td width="100"></td>
  75. </tr>
  76. </thead>
  77. <tbody >
  78. </tbody>
  79. </table></td>
  80. </tr>
  81. <tr>
  82. <td colspan="2" ><label for="textfield"></label>
  83. <input type="text" name="uploadsfile" /></td>
  84. </tr>
  85. <tr>
  86. <td colspan="2" >温馨提示:最多可同时上传 <b ></b> 个文件,只允许上传 <b ></b> 文件。 </td>
  87. </tr>
  88. <tr>
  89. <td colspan="2" align="center" ><input type="button" value="开始上传" disabled="disabled" />
  90. &nbsp;&nbsp;&nbsp;
  91. <input type="button" value="全部取消" disabled="disabled" />
  92. </td>
  93. </tr>
  94. </tbody>
  95. </table>
  96. </form>
  97. <script type="text/javascript">
  98. var isie = (document.all) ? true : false;
  99. var $ = function (id) {
  100. return "string" == typeof id ? document.getelementbyid(id) : id;
  101. };
  102. var class = {
  103. create: function() {
  104. return function() {
  105. this.initialize.apply(this, arguments);
  106. }
  107. }
  108. }
  109. var extend = function(destination, source) {
  110. for (var property in source) {
  111. destination[property] = source[property];
  112. }
  113. }
  114. var bind = function(object, fun) {
  115. return function() {
  116. return fun.apply(object, arguments);
  117. }
  118. }
  119. var each = function(list, fun){
  120. for (var i = 0, len = list.length; i < len; i++) { fun(list[i], i); }
  121. };
  122. //文件上传类
  123. var fileupload = class.create();
  124. fileupload.prototype = {
  125. //表单对象,文件控件存放空间
  126. initialize: function(form, folder, options) {
  127. this.form = $(form);//表单
  128. this.folder = $(folder);//文件控件存放空间
  129. this.files = [];//文件集合
  130. this.setoptions(options);
  131. this.filename = this.options.filename;
  132. this._framename = this.options.framename;
  133. this.limit = this.options.limit;
  134. this.distinct = !!this.options.distinct;
  135. this.extin = this.options.extin;
  136. this.extout = this.options.extout;
  137. this.oninifile = this.options.oninifile;
  138. this.onempty = this.options.onempty;
  139. this.onnotextin = this.options.onnotextin;
  140. this.onextout = this.options.onextout;
  141. this.onlimite = this.options.onlimite;
  142. this.onsame = this.options.onsame;
  143. this.onfail = this.options.onfail;
  144. this.onini = this.options.onini;
  145. if(!this._framename){
  146. //为每个实例创建不同的iframe
  147. this._framename = "uploadframe_" + math.floor(math.random() * 1000);
  148. //ie不能修改iframe的name
  149. var oframe = isie ? document.createelement("<iframe name="" + this._framename + "">") : document.createelement("iframe");
  150. //为ff设置name
  151. oframe.name = this._framename;
  152. oframe.style.display = "none";
  153. //在ie文档未加载完用appendchild会报错
  154. document.body.insertbefore(oframe, document.body.childnodes[0]);
  155. }//开源代码phpfensi.com
  156. //设置form属性,关键是target要指向iframe
  157. this.form.target = this._framename;
  158. this.form.method = "post";
  159. //注意ie的form没有enctype属性,要用encoding
  160. this.form.encoding = "multipart/form-data";
  161. //整理一次
  162. this.ini();
  163. },
  164. //设置默认属性
  165. setoptions: function(options) {
  166. this.options = {//默认值
  167. filename: "files[]",//文件上传控件的name,配合后台使用
  168. framename: "",//iframe的name,要自定义iframe的话这里设置name
  169. oninifile: function(){},//整理文件时执行(其中参数是file对象)
  170. onempty: function(){},//文件空值时执行
  171. limit: 10,//文件数限制,0为不限制
  172. onlimite: function(){},//超过文件数限制时执行
  173. distinct: true,//是否不允许相同文件
  174. onsame: function(){},//有相同文件时执行
  175. extin: ["gif","jpg","rar","zip","iso","swf","exe"],//允许后缀名
  176. onnotextin: function(){},//不是允许后缀名时执行
  177. extout: [],//禁止后缀名,当设置了extin则extout无效
  178. onextout: function(){},//是禁止后缀名时执行
  179. onfail: function(){},//文件不通过检测时执行(其中参数是file对象)
  180. onini: function(){}//重置时执行
  181. };
  182. extend(this.options, options || {});
  183. },
  184. //整理空间
  185. ini: function() {
  186. //整理文件集合
  187. this.files = [];
  188. //整理文件空间,把有值的file放入文件集合
  189. each(this.folder.getelementsbytagname("input"), bind(this, function(o){
  190. if(o.type == "file"){ o.value && this.files.push(o); this.oninifile(o); }
  191. }))
  192. //插入一个新的file
  193. var file = document.createelement("input");
  194. file.name = this.filename; file.type = "file"; file.onchange = bind(this, function(){ this.check(file); this.ini(); });
  195. this.folder.appendchild(file);
  196. //执行附加程序
  197. this.onini();
  198. },
  199. //检测file对象
  200. check: function(file) {
  201. //检测变量
  202. var bcheck = true;
  203. //空值、文件数限制、后缀名、相同文件检测
  204. if(!file.value){
  205. bcheck = false; this.onempty();
  206. } else if(this.limit && this.files.length >= this.limit){
  207. bcheck = false; this.onlimite();
  208. } else if(!!this.extin.length && !regexp(".(" + this.extin.join("|") + ")$", "i").test(file.value)){
  209. //检测是否允许后缀名
  210. bcheck = false; this.onnotextin();
  211. } else if(!!this.extout.length && regexp(".(" + this.extout.join("|") + ")$", "i").test(file.value)) {
  212. //检测是否禁止后缀名
  213. bcheck = false; this.onextout();
  214. } else if(!!this.distinct) {
  215. each(this.files, function(o){ if(o.value == file.value){ bcheck = false; } })
  216. if(!bcheck){ this.onsame(); }
  217. }
  218. //没有通过检测
  219. !bcheck && this.onfail(file);
  220. },
  221. //删除指定file
  222. delete: function(file) {
  223. //移除指定file
  224. this.folder.removechild(file); this.ini();
  225. },
  226. //删除全部file
  227. clear: function() {
  228. //清空文件空间
  229. each(this.files, bind(this, function(o){ this.folder.removechild(o); })); this.ini();
  230. }
  231. }
  232. var fu = new fileupload("uploadform", "idfile", { extin: ["gif","jpg"],
  233. oninifile: function(file){ file.value ? file.style.display = "none" : this.folder.removechild(file); },
  234. onempty: function(){ alert("请选择一个文件"); },
  235. onlimite: function(){ alert("超过上传限制"); },
  236. onsame: function(){ alert("已经有相同文件"); },
  237. onnotextin: function(){ alert("只允许上传" + this.extin.join(",") + "文件"); },
  238. onfail: function(file){ this.folder.removechild(file); },
  239. onini: function(){
  240. //显示文件列表
  241. var arrrows = [];
  242. if(this.files.length){
  243. var othis = this;
  244. each(this.files, function(o){
  245. var a = document.createelement("a"); a.innerhtml = "取消"; a.href = "javascript:void(0);";
  246. a.onclick = function(){ othis.delete(o); return false; };
  247. arrrows.push([o.value, a]);
  248. });
  249. } else { arrrows.push(["<font color='gray'>没有添加文件</font>", "&nbsp;"]); }
  250. addlist(arrrows);
  251. //设置按钮
  252. $("idbtnupload").disabled = $("idbtndel").disabled = this.files.length <= 0;
  253. }
  254. });
  255. $("idbtnupload").onclick = function(){
  256. //显示文件列表
  257. var arrrows = [];
  258. each(fu.files, function(o){ arrrows.push([o.value, "&nbsp;"]); });
  259. addlist(arrrows);
  260. fu.folder.style.display = "none";
  261. $("idprocess").style.display = "";
  262. $("idmsg").innerhtml = "正在添加文件到您的网盘中,请稍候……<br />有可能因为网络问题,出现程序长时间无响应,请点击"<a href='?'><font color='red'>取消</font></a>"重新上传文件";
  263. fu.form.submit();
  264. }
  265. //用来添加文件列表的函数
  266. function addlist(rows){
  267. //根据数组来添加列表
  268. var filelist = $("idfilelist"), ofragment = document.createdocumentfragment();
  269. //用文档碎片保存列表
  270. each(rows, function(cells){
  271. var row = document.createelement("tr");
  272. each(cells, function(o){
  273. var cell = document.createelement("td");
  274. if(typeof o == "string"){ cell.innerhtml = o; }else{ cell.appendchild(o); }
  275. row.appendchild(cell);
  276. });
  277. ofragment.appendchild(row);
  278. })
  279. //ie的table不支持innerhtml所以这样清空table
  280. while(filelist.haschildnodes()){ filelist.removechild(filelist.firstchild); }
  281. filelist.appendchild(ofragment);
  282. }
  283. $("idlimit").innerhtml = fu.limit;
  284. $("idext").innerhtml = fu.extin.join(",");
  285. $("idbtndel").onclick = function(){ fu.clear(); }
  286. //在后台通过window.parent来访问主页面的函数
  287. function finish(msg)
  288. {
  289. $('uploadsfile').value=msg;
  290. }
  291. </script>
  292. </body>
  293. </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. $uploadfile=$uploaddir.strtolower(basename($f_name));
  19. $tmp_type=substr(strrchr($f_name,"."),1);//获取文件扩展名
  20. $tmp_type=strtolower($tmp_type);
  21. if(!stristr($f_type,$tmp_type)){
  22. echo "<script>alert('对不起,不能上传".$tmp_type."格式文件, ".$f_name." 文件上传失败!')</script>";
  23. $up_error="yes";
  24. }
  25. if ($_files[$f_input]['size'][$key]>$file_size_max) {
  26. echo "<script>alert('对不起,你上传的文件 ".$f_name." 容量为".round($_files[$f_input]
  27. ['size'][$key]/1024)."kb,大于规定的".($file_size_max/1024)."kb,上传失败!')</script>";
  28. $up_error="yes";
  29. }
  30. if (file_exists($uploadfile)&&!$overwrite){
  31. echo "<script>alert('对不起,文件 ".$f_name." 已经存在,上传失败!')</script>";
  32. $up_error="yes";
  33. }
  34. $string = 'abcdefghijklmnopgrstuvwxyz0123456789';
  35. $rand = '';
  36. for ($x=0;$x<12;$x++)
  37. $rand .= substr($string,mt_rand(0,strlen($string)-1),1);
  38. $t=date("ymdhis").substr($gettime[0],2,6).$rand;
  39. $attdir="./file/";
  40. if(!is_dir($attdir))
  41. { mkdir($attdir);}
  42. $uploadfile=$attdir.$t.".".$tmp_type;
  43. if(($up_error!="yes") and (move_uploaded_file($_files[$f_input]['tmp_name']
  44. [$key], $uploadfile))){
  45. $_msg=$_msg.$f_name.'上传成功 ';
  46. }
  47. else{
  48. $_msg=$_msg.$f_name.'上传失败 ';
  49. }
  50. }
  51. }
  52. echo "<script>window.parent.finish('".$_msg."');</script>";
  53. ?>
  54. </body>
  55. </html>