PHP Ajax上传文件实例,ajaxfileupload.js

讲过利用jquery ajax与php实现图片上传,下面我介绍利用php ajax实现各种文件无刷新上传,直接放实例希望给各位同学有帮助,可以批量进行添加上传,简单方便,代码如下:

  1. <script type="text/javascript" src="jquery-1.5.1.min.js"></script>
  2. <script type="text/javascript" >
  3. jQuery.extend({
  4. createUploadIframe: function(id, uri)
  5. {
  6. //create frame
  7. var frameId = 'jUploadFrame' + id;
  8. var iframeHtml = '<iframe + frameId + '" name="' + frameId + '" ';
  9. if(window.ActiveXObject)
  10. {
  11. if(typeof uri== 'boolean'){
  12. iframeHtml += ' src="' + 'javascript:false' + '"';
  13. }
  14. else if(typeof uri== 'string'){
  15. iframeHtml += ' src="' + uri + '"';
  16. }
  17. }
  18. iframeHtml += ' />';
  19. jQuery(iframeHtml).appendTo(document.body);
  20. return jQuery('#' + frameId).get(0);
  21. },
  22. createUploadForm: function(id, fileElementId, data)
  23. {
  24. //create form
  25. var formId = 'jUploadForm' + id;
  26. var fileId = 'jUploadFile' + id;
  27. var form = jQuery('<form action="" method="POST" name="' + formId + '" + formId + '" enctype="multipart/form-data"></form>');
  28. if(data)
  29. {
  30. for(var i in data)
  31. {
  32. jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
  33. }
  34. }
  35. var oldElement = jQuery('#' + fileElementId);
  36. var newElement = jQuery(oldElement).clone();
  37. jQuery(oldElement).attr('id', fileId);
  38. jQuery(oldElement).before(newElement);
  39. jQuery(oldElement).appendTo(form);
  40. //set attributes
  41. jQuery(form).css('position', 'absolute');
  42. jQuery(form).css('top', '-1200px');
  43. jQuery(form).css('left', '-1200px');
  44. jQuery(form).appendTo('body');
  45. return form;
  46. },
  47. ajaxFileUpload: function(s) {
  48. // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
  49. s = jQuery.extend({}, jQuery.ajaxSettings, s);
  50. var id = new Date().getTime()
  51. var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
  52. var io = jQuery.createUploadIframe(id, s.secureuri);
  53. var frameId = 'jUploadFrame' + id;
  54. var formId = 'jUploadForm' + id;
  55. // Watch for a new set of requests
  56. if ( s.global && ! jQuery.active++ )
  57. {
  58. jQuery.event.trigger( "ajaxStart" );
  59. }
  60. var requestDone = false;
  61. // Create the request object
  62. var xml = {}
  63. if ( s.global )
  64. jQuery.event.trigger("ajaxSend", [xml, s]);
  65. // Wait for a response to come back
  66. var uploadCallback = function(isTimeout)
  67. {
  68. var io = document.getElementById(frameId);
  69. try
  70. {
  71. if(io.contentWindow)
  72. {
  73. xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
  74. xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
  75. }else if(io.contentDocument)
  76. {
  77. xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
  78. xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
  79. }
  80. }catch(e)
  81. {
  82. jQuery.handleError(s, xml, null, e);
  83. }
  84. if ( xml || isTimeout == "timeout")
  85. {
  86. requestDone = true;
  87. var status;
  88. try {
  89. status = isTimeout != "timeout" ? "success" : "error";
  90. // Make sure that the request was successful or notmodified
  91. if ( status != "error" )
  92. {
  93. // process the data (runs the xml through httpData regardless of callback)
  94. var data = jQuery.uploadHttpData( xml, s.dataType );
  95. // If a local callback was specified, fire it and pass it the data
  96. if ( s.success )
  97. s.success( data, status );
  98. // Fire the global callback
  99. if( s.global )
  100. jQuery.event.trigger( "ajaxSuccess", [xml, s] );
  101. } else
  102. jQuery.handleError(s, xml, status);
  103. } catch(e)
  104. {
  105. status = "error";
  106. jQuery.handleError(s, xml, status, e);
  107. }
  108. // The request was completed
  109. if( s.global )
  110. jQuery.event.trigger( "ajaxComplete", [xml, s] );
  111. // Handle the global AJAX counter
  112. if ( s.global && ! --jQuery.active )
  113. jQuery.event.trigger( "ajaxStop" );
  114. // Process result
  115. if ( s.complete )
  116. s.complete(xml, status);
  117. jQuery(io).unbind()
  118. setTimeout(function()
  119. { try
  120. {
  121. jQuery(io).remove();
  122. jQuery(form).remove();
  123. } catch(e)
  124. {
  125. jQuery.handleError(s, xml, null, e);
  126. }
  127. }, 100)
  128. xml = null
  129. }
  130. }
  131. // Timeout checker
  132. if ( s.timeout > 0 )
  133. {
  134. setTimeout(function(){
  135. // Check to see if the request is still happening
  136. if( !requestDone ) uploadCallback( "timeout" );
  137. }, s.timeout);
  138. }
  139. try
  140. {
  141. var form = jQuery('#' + formId);
  142. jQuery(form).attr('action', s.url);
  143. jQuery(form).attr('method', 'POST');
  144. jQuery(form).attr('target', frameId);
  145. if(form.encoding)
  146. {
  147. jQuery(form).attr('encoding', 'multipart/form-data');
  148. }
  149. else
  150. {
  151. jQuery(form).attr('enctype', 'multipart/form-data');
  152. }
  153. jQuery(form).submit();
  154. } catch(e)
  155. {
  156. jQuery.handleError(s, xml, null, e);
  157. }
  158. jQuery('#' + frameId).load(uploadCallback );
  159. return {abort: function () {}};
  160. },
  161. uploadHttpData: function( r, type ) {
  162. var data = !type;
  163. data = type == "xml" || data ? r.responseXML : r.responseText;
  164. // If the type is "script", eval it in global context
  165. if ( type == "script" )
  166. jQuery.globalEval( data );
  167. // Get the JavaScript object, if JSON is used.
  168. if ( type == "json" )
  169. eval( "data = " + data );
  170. // evaluate scripts within html
  171. if ( type == "html" )
  172. jQuery("<div>").html(data).evalScripts();
  173. return data;
  174. }
  175. })
  176. </script>
  177. <form action="" method="post" enctype="multipart/form-data">
  178. <input size='80' /><br> <input type="file" name="file1"
  179. size="30" /> <input type="button" value="上传"
  180. onclick="return ajaxFileUpload();" /> <span
  181. >UpLoading...</span>
  182. </form>
  183. <script type="text/javascript">
  184. var str = '';
  185. function ajaxFileUpload(){
  186. $("#msg")
  187. .ajaxStart(function(){
  188. $(this).show();
  189. });
  190. /*
  191. .ajaxComplete(function(){
  192. $(this).hide();
  193. });
  194. */
  195. $.ajaxFileUpload(
  196. {
  197. url:'up_deal.php',
  198. secureuri:false,
  199. fileElementId:'file1',
  200. dataType: 'text',
  201. //data:{name:'qinmi', id:'123'},
  202. success: function(data){
  203. if(data=='error'){
  204. $('#msg').html("<span >上传失败</span>");
  205. }else{
  206. $('#msg').html("<span >上传成功</span>");
  207. str += data+'@';
  208. $('#fname').val(str);
  209. }
  210. }
  211. }
  212. );
  213. return false;
  214. }
  215. </script>

up_deal.php,代码如下:

  1. <?php
  2. if ((($_FILES["file1"]["type"] == "image/gif")
  3. || ($_FILES["file1"]["type"] == "image/jpeg")
  4. || ($_FILES["file1"]["type"] == "image/bmp")
  5. || ($_FILES["file1"]["type"] == "image/pjpeg"))
  6. && ($_FILES["file1"]["size"] < 100000)){//100KB
  7. $extend = explode(".",$_FILES["file1"]["name"]);
  8. $key = count($extend)-1;
  9. $ext = ".".$extend[$key];
  10. $newfile = time().$ext;
  11. //开源代码phpfensi.com
  12. if(!file_exists('upload')){mkdir('upload');}
  13. move_uploaded_file($_FILES["file1"]["tmp_name"],"upload/" . $newfile);
  14. @unlink($_FILES['file1']);
  15. echo $newfile;
  16. }else {
  17. echo 'error';
  18. }
  19. ?>