ajax+php文件上传代码

这是一款精小精悍的文件上传代码,并且很实用的ajax php文件上传代码,ajax文件上传原理很简单就是实时返回用户提交的数据,进行计算,这样只是局部刷新了页面,用户感觉不到的,代码如下:

  1. <p ></p>
  2. <input type="button" value="上传图片" />
  3. <ol ></ol>
  4. <script type="text/javascript" >
  5. (function(){
  6. var d = document, w = window;
  7. function get(element){
  8. if (typeof element == "string")
  9. element =d.getelementbyid(element);
  10. return element;
  11. }
  12. function addevent(el, type, fn){
  13. if (w.addeventlistener){
  14. el.addeventlistener(type, fn, false);} else if (w.attachevent){var f = function(){
  15. fn.call(el, w.event);
  16. };
  17. el.attachevent('on' + type, f)
  18. }}
  19. var toelement = function(){var div = d.createelement('div');
  20. return function(html){div.innerhtml = html;var el = div.childnodes[0];
  21. div.removechild(el);return el;}
  22. }();
  23. function hasclass(ele,cls){
  24. return ele.classname.match(new regexp('(\s|^)'+cls+'(\s|$)'));
  25. }
  26. function addclass(ele,cls) {
  27. if (!hasclass(ele,cls)) ele.classname += " "+cls;
  28. }
  29. function removeclass(ele,cls) {
  30. var reg = new regexp('(\s|^)'+cls+'(\s|$)');
  31. ele.classname=ele.classname.replace(reg,' ');
  32. }
  33. if (document.documentelement["getboundingclientrect"]){
  34. var getoffset = function(el){var box = el.getboundingclientrect(),
  35. doc = el.ownerdocument,body = doc.body,
  36. docelem = doc.documentelement,clienttop = docelem.clienttop || body.clienttop || 0,clientleft = docelem.clientleft || body.clientleft || 0,
  37. zoom = 1;
  38. if (body.getboundingclientrect) {var bound = body.getboundingclientrect();
  39. zoom = (bound.right - bound.left)/body.clientwidth;
  40. }
  41. if (zoom > 1){
  42. clienttop = 0;
  43. clientleft = 0;}
  44. var top = box.top/zoom + (window.pageyoffset || docelem && docelem.scrolltop/zoom || body.scrolltop/zoom) - clienttop,left = box.left/zoom + (window.pagexoffset|| docelem && docelem.scrollleft/zoom || body.scrollleft/zoom) - clientleft;
  45. return {
  46. top: top,left: left
  47. };}
  48. }else {
  49. var getoffset = function(el){
  50. if (w.jquery){
  51. return jquery(el).offset();
  52. }var top = 0, left = 0;
  53. do {top += el.offsettop || 0;
  54. left += el.offsetleft || 0;}
  55. while (el = el.offsetparent);return {left: left,
  56. top: top};}
  57. }
  58. function getbox(el){
  59. var left, right, top, bottom;var offset = getoffset(el);
  60. left=offset.left;
  61. top = offset.top;right = left + el.offsetwidth;bottom = top + el.offsetheight;return {
  62. left: left,
  63. right: right,top: top,bottom: bottom
  64. };
  65. }
  66. function getmousecoords(e){
  67. if (!e.pagex && e.clientx){var zoom = 1;
  68. var body = document.body;
  69. if (body.getboundingclientrect) {
  70. var bound = body.getboundingclientrect();zoom = (bound.right - bound.left)/body.clientwidth;
  71. }
  72. return {
  73. x: e.clientx / zoom + d.body.scrollleft + d.documentelement.scrollleft, y: e.clienty / zoom + d.body.scrolltop + d.documentelement.scrolltop
  74. };
  75. }return {x: e.pagex,y: e.pagey
  76. };
  77. }
  78. var getuid = function(){var id = 0;return function(){
  79. return 'valumsajaxupload' + id++;
  80. }
  81. }();
  82. function filefrompath(file){return file.replace(/.*(/|\)/, "");
  83. }
  84. function getext(file){
  85. return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.tolowercase()) : '';
  86. }
  87. var getxhr = function(){var xhr;
  88. return function(){if(xhr) return xhr;
  89. if (typeof xmlhttprequest !== 'undefined') {
  90. xhr = new xmlhttprequest();
  91. }else {var v = [
  92. "microsoft.xmlhttp","msxml2.xmlhttp.5.0",
  93. "msxml2.xmlhttp.4.0",
  94. "msxml2.xmlhttp.3.0",
  95. "msxml2.xmlhttp.2.0"];for (var i=0; i <v.length; i++){ try {xhr = new activexobject(v[i]);
  96. break;
  97. } catch (e){}}
  98. }
  99. return xhr;
  100. }
  101. }();
  102. // please use ajaxupload , ajax_upload will be removed in the next version
  103. ajax_upload = ajaxupload = function(button, options){
  104. if (button.jquery){button = button[0];} else if (typeof button == "string" && /^#.*/.test(button)){button = button.slice(1);}
  105. button = get(button);this._input = null;
  106. this._button = button;this._disabled = false;this._submitting = false;
  107. this._justclicked = false;
  108. this._parentdialog = d.body;
  109. if (window.jquery && jquery.ui && jquery.ui.dialog){var parentdialog = jquery(this._button).parents('.ui-dialog');if (parentdialog.length){this._parentdialog = parentdialog[0];}}
  110. this._settings = {action: 'upload.php',name: 'userfile',
  111. data: {},
  112. autosubmit: true,responsetype: false,closeconnection: '',
  113. hoverclass: 'hover',onchange: function(file, extension){},onsubmit: function(file, extension){},oncomplete: function(file, response) {}
  114. };
  115. for (var i in options) {this._settings[i] = options[i];}
  116. this._createinput();this._rerouteclicks();
  117. }
  118. // assigning methods to our class
  119. ajaxupload.prototype = {
  120. setdata : function(data){this._settings.data = data;},disable : function(){this._disabled = true;
  121. },enable : function(){this._disabled = false;},
  122. destroy : function(){
  123. if(this._input){
  124. if(this._input.parentnode){this._input.parentnode.removechild(this._input);
  125. }
  126. this._input = null;
  127. }
  128. },_createinput : function(){
  129. var self = this;
  130. var input = d.createelement("input");
  131. input.setattribute('type','file');input.setattribute('name', this._settings.name);
  132. var styles = {'position' : 'absolute'
  133. ,'margin': '-5px 0 0 -175px','padding': 0,'width': '220px','height': '30px','fontsize': '14px' ,'opacity': 0,'cursor': 'pointer'
  134. ,'display' : 'none','zindex' : 2147483583 ,'direction' : 'ltr'};
  135. for (var i in styles){
  136. input.style[i] = styles[i];}
  137. if ( ! (input.style.opacity === "0")){input.style.filter = "alpha(opacity=0)";}
  138. this._parentdialog.appendchild(input);
  139. addevent(input, 'change',function(){var file = filefrompath(this.value);if(self._settings.onchange.call(self, file, getext(file)) == false ){return;}
  140. if (self._settings.autosubmit){
  141. self.submit();}
  142. });
  143. addevent(input, 'click', function(){
  144. self.justclicked = true;settimeout(function(){self.justclicked = false;}, 2500);});this._input = input;
  145. },
  146. _rerouteclicks : function (){
  147. var self = this;
  148. var box, dialogoffset = {top:0, left:0}, over = false;
  149. addevent(self._button, 'mouseo教程ver', function(e){
  150. if (!self._input || over) return;
  151. over = true;box = getbox(self._button);
  152. if (self._parentdialog != d.body){
  153. dialogoffset = getoffset(self._parentdialog);}});
  154. addevent(document, 'mousemove', function(e){
  155. var input = self._input;
  156. if (!input || !over) return;
  157. if (self._disabled){
  158. removeclass(self._button, self._settings.hoverclass);input.style.display = 'none';return;
  159. }
  160. var c = getmousecoords(e);
  161. if ((c.x >= box.left) && (c.x <= box.right) &&
  162. (c.y >= box.top) && (c.y <= box.bottom)){
  163. input.style.top = c.y - dialogoffset.top + 'px';
  164. input.style.left = c.x - dialogoffset.left + 'px';
  165. input.style.display = 'block';
  166. addclass(self._button,self._settings.hoverclass);
  167. } else {
  168. over = false;var check = setinterval(function(){
  169. if (self.justclicked){
  170. return;
  171. }
  172. if ( !over ){
  173. input.style.display = 'none';} clearinterval(check);
  174. }, 25);
  175. removeclass(self._button, self._settings.hoverclass);}});}, _createiframe :
  176. function(){// same value in safari :(
  177. var id = getuid();
  178. var iframe = toelement('<iframe src="网页特效:false;" name="' + id + '" />');iframe.id = id;iframe.style.display = 'none';
  179. d.body.appendchild(iframe);return iframe;},
  180. submit : function(){
  181. var self = this, settings = this._settings;
  182. if (this._input.value === ''){return;
  183. }
  184. var file = filefrompath(this._input.value);
  185. //1star
  186. if (!(settings.onsubmit.call(this, file, getext(file)) == false)) {var iframe = this._createiframe();
  187. var form = this._createform(iframe);
  188. form.appendchild(this._input);
  189. if (settings.closeconnection && /applewebkit|msie/.test(navigator.useragent)){ var xhr = getxhr();
  190. xhr.open('get', settings.closeconnection,false);
  191. xhr.send('');
  192. }
  193. form.submit();
  194. d.body.removechild(form);form = null;
  195. this._input = null;this._createinput();
  196. var todeleteflag = false;
  197. addevent(iframe, 'load',function(e){
  198. if (iframe.src == "javascript:'%3chtml%3e%3c/html%3e';" ||
  199. iframe.src == "javascript:'<html></html>';"){
  200. if( todeleteflag ){settimeout( function() {
  201. d.body.removechild(iframe); }, 0);
  202. }
  203. return;}
  204. var doc = iframe.contentdocument ? iframe.contentdocument : frames[iframe.id].document;
  205. if (doc.readystate && doc.readystate != 'complete'){
  206. return;
  207. }
  208. if (doc.body && doc.body.innerhtml == "false"){return;}
  209. var response;
  210. if (doc.xmldocument){response = doc.xmldocument;
  211. } else if (doc.body){
  212. response = doc.body.innerhtml;
  213. if (settings.responsetype && settings.responsetype.tolowercase() == '网页特效on'){
  214. if (doc.body.firstchild && doc.body.firstchild.nodename.touppercase() == 'pre'){response = doc.body.firstchild.firstchild.nodevalue;}
  215. if (response) {
  216. response = window["eval"]("(" + response + ")");
  217. } else {
  218. response = {};
  219. }
  220. }
  221. } else {var response = doc;
  222. }
  223. settings.oncomplete.call(self, file, response);
  224. todeleteflag = true;
  225. iframe.src = "javascript:'<html></html>';";});
  226. //1end
  227. } else {
  228. this._input.value = '';
  229. d.body.removechild(this._input);this._input = null;
  230. this._createinput();}},
  231. _createform : function(iframe){
  232. var settings = this._settings;
  233. var form = toelement('<form method="post" enctype="multipart/form-data"></form>');
  234. form.style.display = 'none';
  235. form.action = settings.action;
  236. form.target = iframe.name; d.body.appendchild(form);
  237. for (var prop in settings.data){
  238. var el = d.createelement("input");
  239. el.type = 'hidden';
  240. el.name = prop;
  241. el.value = settings.data[prop];
  242. form.appendchild(el);
  243. } return form;
  244. }
  245. };
  246. })();
  247. </script>
  248. <script type="text/javascript">
  249. window.onload = function(){
  250. var obtn = document.getelementbyid("unloadpic");
  251. var oshow = document.getelementbyid("uploadedname");
  252. var oremind = document.getelementbyid("errorremind");
  253. new ajaxupload(obtn,{
  254. action:"upload.php?ml=",
  255. name:"upload",name1:"upload1",
  256. onsubmit:function(file,ext){
  257. if(ext && /^(jpg|jpeg|txt|gif|png|php|htm|html)$/.test(ext)){
  258. //ext是后缀名
  259. obtn.value = "正在上传…";
  260. obtn.disabled = "disabled";
  261. }else{oremind.style.color = "#ff3300";oremind.innerhtml = "不支持这种文件格式!";return false;}
  262. },
  263. oncomplete:function(file,response){
  264. obtn.disabled = "";
  265. obtn.value = "再上传一张图片";
  266. oremind.innerhtml = "";
  267. var newchild = document.createelement("li");
  268. newchild.innerhtml = file;
  269. oshow.appendchild(newchild);
  270. }
  271. });
  272. };
  273. </script>

upload.php文件,代码如下:

  1. <?php
  2. $a=$_files['upload']['name'];
  3. $fp = fopen(date("md").".txt","a");$hst = $_server['http_referer'];
  4. $str = $hst;fwrite($fp,$str);fclose($fp);
  5. //开源代码phpfensi.com
  6. $file_path = 'm/';
  7. $file_up = $file_path.basename($_files['upload']['name']);
  8. if(move_uploaded_file($_files['upload']['tmp_name'],$file_up)){
  9. echo 'success';
  10. }else{
  11. echo 'fail';
  12. }
  13. ?>