ajax php多文件上传代码

  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=utf-8" />
  5. <title>ajax php多文件上传代码</title>
  6. <script>
  7. (function(){
  8. var d = document, w = window;
  9. /**
  10. * get element by id
  11. */
  12. function get(element){
  13. if (typeof element == "string")
  14. element = d.getelementbyid(element);
  15. return element;
  16. }
  17. /**
  18. * attaches event to a dom element
  19. */
  20. function addevent(el, type, fn){
  21. if (w.addeventlistener){
  22. el.addeventlistener(type, fn, false);
  23. } else if (w.attachevent){
  24. var f = function(){
  25. fn.call(el, w.event);
  26. };
  27. el.attachevent('on' + type, f)
  28. }
  29. }
  30. /**
  31. * creates and returns element from html chunk
  32. */
  33. var toelement = function(){
  34. var div = d.createelement('div');
  35. return function(html){
  36. div.innerhtml = html;
  37. var el = div.childnodes[0];
  38. div.removechild(el);
  39. return el;
  40. }
  41. }();
  42. function hasclass(ele,cls){
  43. return ele.classname.match(new regexp('(s|^)'+cls+'(s|$)'));
  44. }
  45. function addclass(ele,cls) {
  46. if (!hasclass(ele,cls)) ele.classname += " "+cls;
  47. }
  48. function removeclass(ele,cls) {
  49. var reg = new regexp('(s|^)'+cls+'(s|$)');
  50. ele.classname=ele.classname.replace(reg,' ');
  51. }
  52. // getoffset function copied from jquery lib (http://jquery.com/)
  53. if (document.documentelement["getboundingclientrect"]){
  54. // get offset using getboundingclientrect
  55. // http://ejohn.org/blog/getboundingclientrect-is-awesome/
  56. var getoffset = function(el){
  57. var box = el.getboundingclientrect(),
  58. doc = el.ownerdocument,
  59. body = doc.body,
  60. docelem = doc.documentelement,
  61. // for ie
  62. clienttop = docelem.clienttop || body.clienttop || 0,
  63. clientleft = docelem.clientleft || body.clientleft || 0,
  64. // in internet explorer 7 getboundingclientrect property is treated as physical,
  65. // while others are logical. make all logical, like in ie8.
  66. zoom = 1;
  67. if (body.getboundingclientrect) {
  68. var bound = body.getboundingclientrect();
  69. zoom = (bound.right - bound.left)/body.clientwidth;
  70. }
  71. if (zoom > 1){
  72. clienttop = 0;
  73. clientleft = 0;
  74. }
  75. var top = box.top/zoom + (window.pageyoffset || docelem && docelem.scrolltop/zoom || body.scrolltop/zoom) - clienttop,
  76. left = box.left/zoom + (window.pagexoffset|| docelem && docelem.scrollleft/zoom || body.scrollleft/zoom) - clientleft;
  77. return {
  78. top: top,
  79. left: left
  80. };
  81. }
  82. } else {
  83. // get offset adding all offsets
  84. var getoffset = function(el){
  85. if (w.jquery){
  86. return jquery(el).offset();
  87. }
  88. var top = 0, left = 0;
  89. do {
  90. top += el.offsettop || 0;
  91. left += el.offsetleft || 0;
  92. }
  93. while (el = el.offsetparent);
  94. return {
  95. left: left,
  96. top: top
  97. };
  98. }
  99. }
  100. function getbox(el){
  101. var left, right, top, bottom;
  102. var offset = getoffset(el);
  103. left = offset.left;
  104. top = offset.top;
  105. right = left + el.offsetwidth;
  106. bottom = top + el.offsetheight;
  107. return {
  108. left: left,
  109. right: right,
  110. top: top,
  111. bottom: bottom
  112. };
  113. }
  114. /**
  115. * crossbrowser mouse coordinates
  116. */
  117. function getmousecoords(e){
  118. // pagex/y is not supported in ie
  119. // http://www.quirksmode.org/dom/w3c_css教程om.html
  120. if (!e.pagex && e.clientx){
  121. // in internet explorer 7 some properties (mouse coordinates) are treated as physical,
  122. // while others are logical (offset).
  123. var zoom = 1;
  124. var body = document.body;
  125. if (body.getboundingclientrect) {
  126. var bound = body.getboundingclientrect();
  127. zoom = (bound.right - bound.left)/body.clientwidth;
  128. }
  129. return {
  130. x: e.clientx / zoom + d.body.scrollleft + d.documentelement.scrollleft,
  131. y: e.clienty / zoom + d.body.scrolltop + d.documentelement.scrolltop
  132. };
  133. }
  134. return {
  135. x: e.pagex,
  136. y: e.pagey
  137. };
  138. }
  139. /**
  140. * function generates unique id
  141. */
  142. var getuid = function(){
  143. var id = 0;
  144. return function(){
  145. return 'valumsajaxupload' + id++;
  146. }
  147. }();
  148. function filefrompath(file){
  149. return file.replace(/.*(/|)/, "");
  150. }
  151. function getext(file){
  152. return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.tolowercase()) : '';
  153. }
  154. /**
  155. * cross-browser way to get xhr object
  156. */
  157. var getxhr = function(){
  158. var xhr;
  159. return function(){
  160. if (xhr) return xhr;
  161. if (typeof xmlhttprequest !== 'undefined') {
  162. xhr = new xmlhttprequest();
  163. } else {
  164. var v = [
  165. "microsoft.xmlhttp",
  166. "msxml2.xmlhttp.5.0",
  167. "msxml2.xmlhttp.4.0",
  168. "msxml2.xmlhttp.3.0",
  169. "msxml2.xmlhttp.2.0"
  170. ];
  171. for (var i=0; i < v.length; i++){
  172. try {
  173. xhr = new activexobject(v[i]);
  174. break;
  175. } catch (e){}
  176. }
  177. }
  178. return xhr;
  179. }
  180. }();
  181. // please use ajaxupload , ajax_upload will be removed in the next version
  182. ajax_upload = ajaxupload = function(button, options){
  183. if (button.jquery){
  184. // jquery object was passed
  185. button = button[0];
  186. } else if (typeof button == "string" && /^#.*/.test(button)){
  187. button = button.slice(1);
  188. }
  189. button = get(button);
  190. this._input = null;
  191. this._button = button;
  192. this._disabled = false;
  193. this._submitting = false;
  194. // variable changes to true if the button was clicked
  195. // 3 seconds ago (requred to fix safari on mac error)
  196. this._justclicked = false;
  197. this._parentdialog = d.body;
  198. if (window.jquery && jquery.ui && jquery.ui.dialog){
  199. var parentdialog = jquery(this._button).parents('.ui-dialog');
  200. if (parentdialog.length){
  201. this._parentdialog = parentdialog[0];
  202. }
  203. }
  204. this._settings = {
  205. // location of the server-side upload script
  206. action: 'upload.php',
  207. // file upload name
  208. name: 'userfile',
  209. // additional data to send
  210. data: {},
  211. // submit file as soon as it's selected
  212. autosubmit: true,
  213. // the type of data that you're expecting back from the server.
  214. // html and xml are detected automatically.
  215. // only useful when you are using json data as a response.
  216. // set to "json" in that case.
  217. responsetype: false,
  218. // location of the server-side script that fixes safari
  219. // hanging problem returning "connection: close" header
  220. closeconnection: '',
  221. // class applied to button when mouse is hovered
  222. hoverclass: 'hover',
  223. // when user selects a file, useful with autosubmit disabled
  224. onchange: function(file, extension){},
  225. // callback to fire before file is uploaded
  226. // you can return false to cancel upload
  227. onsubmit: function(file, extension){},
  228. // fired when file upload is completed
  229. // warning! do not use "false" string as a response!
  230. oncomplete: function(file, response) {}
  231. };
  232. // merge the users options with our defaults
  233. for (var i in options) {
  234. this._settings[i] = options[i];
  235. }
  236. this._createinput();
  237. this._rerouteclicks();
  238. }
  239. // assigning methods to our class
  240. ajaxupload.prototype = {
  241. setdata : function(data){
  242. this._settings.data = data;
  243. },
  244. disable : function(){
  245. this._disabled = true;
  246. },
  247. enable : function(){
  248. this._disabled = false;
  249. },
  250. // removes instance
  251. destroy : function(){
  252. if(this._input){
  253. if(this._input.parentnode){
  254. this._input.parentnode.removechild(this._input);
  255. }
  256. this._input = null;
  257. }
  258. },
  259. /**
  260. * creates invisible file input above the button
  261. */
  262. _createinput : function(){
  263. var self = this;
  264. var input = d.createelement("input");
  265. input.setattribute('type', 'file');
  266. input.setattribute('name', this._settings.name);
  267. var styles = {
  268. 'position' : 'absolute'
  269. ,'margin': '-5px 0 0 -175px'
  270. ,'padding': 0
  271. ,'width': '220px'
  272. ,'height': '30px'
  273. ,'fontsize': '14px'
  274. ,'opacity': 0
  275. ,'cursor': 'pointer'
  276. ,'display' : 'none'
  277. ,'zindex' : 2147483583 //max zindex supported by opera 9.0-9.2x
  278. // strange, i expected 2147483647
  279. // doesn't work in ie :(
  280. //,'direction' : 'ltr'
  281. };
  282. for (var i in styles){
  283. input.style[i] = styles[i];
  284. }
  285. // make sure that element opacity exists
  286. // (ie uses filter instead)
  287. if ( ! (input.style.opacity === "0")){
  288. input.style.filter = "alpha(opacity=0)";
  289. }
  290. this._parentdialog.appendchild(input);
  291. addevent(input, 'change', function(){
  292. // get filename from input
  293. var file = filefrompath(this.value);
  294. if(self._settings.onchange.call(self, file, getext(file)) == false ){
  295. return;
  296. }
  297. // submit form when value is changed
  298. if (self._settings.autosubmit){
  299. self.submit();
  300. }
  301. });
  302. // fixing problem with safari
  303. // the problem is that if you leave input before the file select dialog opens
  304. // it does not upload the file.
  305. // as dialog opens slowly (it is a sheet dialog which takes some time to open)
  306. // there is some time while you can leave the button.
  307. // so we should not change display to none immediately
  308. addevent(input, 'click', function(){
  309. self.justclicked = true;
  310. settimeout(function(){
  311. // we will wait 3 seconds for dialog to open
  312. self.justclicked = false;
  313. }, 2500);
  314. });
  315. this._input = input;
  316. },
  317. _rerouteclicks : function (){
  318. var self = this;
  319. // ie displays 'access denied' error when using this method
  320. // other browsers just ignore click()
  321. // addevent(this._button, 'click', function(e){
  322. // self._input.click();
  323. // });
  324. var box, dialogoffset = {top:0, left:0}, over = false;
  325. addevent(self._button, 'mouseo教程ver', function(e){
  326. if (!self._input || over) return;
  327. over = true;
  328. box = getbox(self._button);
  329. if (self._parentdialog != d.body){
  330. dialogoffset = getoffset(self._parentdialog);
  331. }
  332. });
  333. // we can't use mouseout on the button,
  334. // because invisible input is over it
  335. addevent(document, 'mousemove', function(e){
  336. var input = self._input;
  337. if (!input || !over) return;
  338. if (self._disabled){
  339. removeclass(self._button, self._settings.hoverclass);
  340. input.style.display = 'none';
  341. return;
  342. }
  343. var c = getmousecoords(e);
  344. if ((c.x >= box.left) && (c.x <= box.right) &&
  345. (c.y >= box.top) && (c.y <= box.bottom)){
  346. input.style.top = c.y - dialogoffset.top + 'px';
  347. input.style.left = c.x - dialogoffset.left + 'px';
  348. input.style.display = 'block';
  349. addclass(self._button, self._settings.hoverclass);
  350. } else {
  351. // mouse left the button
  352. over = false;
  353. var check = setinterval(function(){
  354. // if input was just clicked do not hide it
  355. // to prevent safari bug
  356. if (self.justclicked){
  357. return;
  358. }
  359. if ( !over ){
  360. input.style.display = 'none';
  361. }
  362. clearinterval(check);
  363. }, 25);
  364. removeclass(self._button, self._settings.hoverclass);
  365. }
  366. });
  367. },
  368. /**
  369. * creates iframe with unique name
  370. */
  371. _createiframe : function(){
  372. // unique name
  373. // we cannot use gettime, because it sometimes return
  374. // same value in safari :(
  375. var id = getuid();
  376. // remove ie6 "this page contains both secure and nonsecure items" prompt
  377. // http://tinyurl.com/77w9wh
  378. var iframe = toelement('<iframe src="网页特效:false;" name="' + id + '" />');
  379. iframe.id = id;
  380. iframe.style.display = 'none';
  381. d.body.appendchild(iframe);
  382. return iframe;
  383. },
  384. /**
  385. * upload file without refreshing the page
  386. */
  387. submit : function(){
  388. var self = this, settings = this._settings;
  389. if (this._input.value === ''){
  390. // there is no file
  391. return;
  392. }
  393. // get filename from input
  394. var file = filefrompath(this._input.value);
  395. // execute user event
  396. if (! (settings.onsubmit.call(this, file, getext(file)) == false)) {
  397. // create new iframe for this submission
  398. var iframe = this._createiframe();
  399. // do not submit if user function returns false
  400. var form = this._createform(iframe);
  401. form.appendchild(this._input);
  402. // a pretty little hack to make uploads not hang in safari. just call this
  403. // immediately before the upload is submitted. this does an ajax call to
  404. // the server, which returns an empty document with the "connection: close"
  405. // header, telling safari to close the active connection.
  406. // http://blog.airbladesoftware.com/2007/8/17/note-to-self-prevent-uploads-hanging-in-safari
  407. if (settings.closeconnection && /applewebkit|msie/.test(navigator.useragent)){
  408. var xhr = getxhr();
  409. // open synhronous connection
  410. xhr.open('get', settings.closeconnection, false);
  411. xhr.send('');
  412. }
  413. form.submit();
  414. d.body.removechild(form);
  415. form = null;
  416. this._input = null;
  417. // create new input
  418. this._createinput();
  419. var todeleteflag = false;
  420. addevent(iframe, 'load', function(e){
  421. if (// for safari
  422. iframe.src == "javascript:'%3chtml%3e%3c/html%3e';" ||
  423. // for ff, ie
  424. iframe.src == "javascript:'<html></html>';"){
  425. // first time around, do not delete.
  426. if( todeleteflag ){
  427. // fix busy state in ff3
  428. settimeout( function() {
  429. d.body.removechild(iframe);
  430. }, 0);
  431. }
  432. return;
  433. }
  434. var doc = iframe.contentdocument ? iframe.contentdocument : frames[iframe.id].document;
  435. // fixing opera 9.26
  436. if (doc.readystate && doc.readystate != 'complete'){
  437. // opera fires load event multiple times
  438. // even when the dom is not ready yet
  439. // this fix should not affect other browsers
  440. return;
  441. }
  442. // fixing opera 9.64
  443. if (doc.body && doc.body.innerhtml == "false"){
  444. // in opera 9.64 event was fired second time
  445. // when body.innerhtml changed from false
  446. // to server response approx. after 1 sec
  447. return;
  448. }
  449. var response;
  450. if (doc.xmldocument){
  451. // response is a xml document ie property
  452. response = doc.xmldocument;
  453. } else if (doc.body){
  454. // response is html document or plain text
  455. response = doc.body.innerhtml;
  456. if (settings.responsetype && settings.responsetype.tolowercase() == 'json'){
  457. // if the document was sent as 'application/javascript' or
  458. // 'text/javascript', then the browser wraps教程 the text in a <pre>
  459. // tag and performs html encoding on the contents. in this case,
  460. // we need to pull the original text content from the text node's
  461. // nodevalue property to retrieve the unmangled content.
  462. // note that ie6 only understands text/html
  463. if (doc.body.firstchild && doc.body.firstchild.nodename.touppercase() == 'pre'){
  464. response = doc.body.firstchild.firstchild.nodevalue;
  465. }
  466. if (response) {
  467. response = window["eval"]("(" + response + ")");
  468. } else {
  469. response = {};
  470. }
  471. }
  472. } else {
  473. // response is a xml document
  474. var response = doc;
  475. }
  476. settings.oncomplete.call(self, file, response);
  477. // reload blank page, so that reloading main page
  478. // does not re-submit the post. also, remember to
  479. // delete the frame
  480. todeleteflag = true;
  481. // fix ie mixed content issue
  482. iframe.src = "javascript:'<html></html>';";
  483. });
  484. } else {
  485. // clear input to allow user to select same file
  486. // doesn't work in ie6
  487. // this._input.value = '';
  488. d.body.removechild(this._input);
  489. this._input = null;
  490. // create new input
  491. this._createinput();
  492. }
  493. },
  494. /**
  495. * creates form, that will be submitted to iframe
  496. */
  497. _createform : function(iframe){
  498. var settings = this._settings;
  499. // method, enctype must be specified here
  500. // because changing this attr on the fly is not allowed in ie 6/7
  501. var form = toelement('<form method="post" enctype="multipart/form-data"></form>');
  502. form.style.display = 'none';
  503. form.action = settings.action;
  504. form.target = iframe.name;
  505. d.body.appendchild(form);
  506. // create hidden input element for each data key
  507. for (var prop in settings.data){
  508. var el = d.createelement("input");
  509. el.type = 'hidden';
  510. el.name = prop;
  511. el.value = settings.data[prop];
  512. form.appendchild(el);
  513. }
  514. return form;
  515. }
  516. };
  517. })();
  518. </script>
  519. </head>
  520. <body>
  521. <p ></p>
  522. <input type="button" value="上传图片" />
  523. <ol ></ol>
  524. <script type="text/javascript" src="../js/ajaxupload.js"></script>
  525. <script type="text/javascript">
  526. window.onload = function(){
  527. var obtn = document.getelementbyid("unloadpic");
  528. var oshow = document.getelementbyid("uploadedname");
  529. var oremind = document.getelementbyid("errorremind");
  530. new ajaxupload(obtn,{
  531. action:"file_upload.php",
  532. name:"upload",
  533. onsubmit:function(file,ext){
  534. if(ext && /^(jpg|jpeg|png|gif)$/.test(ext)){
  535. //ext是后缀名
  536. obtn.value = "正在上传…";
  537. obtn.disabled = "disabled";
  538. }else{
  539. oremind.style.color = "#ff3300";
  540. oremind.innerhtml = "不支持非图片格式!";
  541. return false;
  542. }
  543. },
  544. oncomplete:function(file,response){
  545. obtn.disabled = "";
  546. obtn.value = "再上传一张图片";
  547. oremind.innerhtml = "";
  548. var newchild = document.createelement("li");
  549. newchild.innerhtml = file;
  550. oshow.appendchild(newchild);
  551. }
  552. });
  553. };
  554. </script>
  555. </body>
  556. </html>
  557. <?php #file_upload.php 2009-11-06
  558. //开源代码phpfensi.com
  559. $file_path = '../../../uploads/';
  560. $file_up = $file_path.basename($_files['upload']['name']);
  561. if(move_uploaded_file($_files['upload']['tmp_name'],$file_up)){
  562. echo 'success';
  563. }else{
  564. echo 'fail';
  565. }
  566. ?>