代碼結構如下:

1、HTML代碼,沒必要解釋了。
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>文件上傳</title>
6 <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
7 <script src="uploads/ajaxFileUpload.js" type="text/javascript" charset="utf-8"></script>
8 <script type="text/javascript">
9 $(function(){
10 $('#ti').click(function(){
11 var data = { name: 'my name', description: 'short description' }
12 $.ajaxFileUpload({
13 url: 'up.php',
14 secureuri: false,
15 data: data,
16 fileElementId: 'upf',
17 dataType: 'json',
18 success: function (data) {
19 // var datejson=eval(data);
20 //console.log(data[0].path_name)
21 $('#im').append('<img src="'+data[0].path_name+'">')
22 //console.log('<img src="'+data[0].path_name+'">')
23 },
24 error: function (data) {
25 console.log(data)
26 }
27 });
28
29 })
30
31 })
32 </script>
33 </head>
34 <body>
35 <!--<form action="up.php" method="post" enctype="multipart/form-data">
36 </form>-->
37 <input type="file" name="upfm" id="upf" value="" />
38 <input id='ti' type="button" value="提交"/>
39
40 <div id="im">
41
42 </div>
43
44 </body>
45
46 </html>
2、關於ajaxFileUpload插件,在下面代碼中如果你使用的是JQ1.9以上請復制1-12到你的ajaxFileUpload代碼中,JQ在很早就廢棄了handleError方法。注釋關於代碼的解釋很清楚。
1 jQuery.extend({
2 handleError: function( s, xhr, status, e ) {
3
4 if ( s.error ) {
5 s.error.call( s.context || s, xhr, status, e );
6 }
7
8
9 if ( s.global ) {
10 (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
11 }
12 },
13 createUploadIframe: function (id, uri) {//id為當前系統時間字符串,uri是外部傳入的json對象的一個參數
14 //create frame
15 var frameId = 'jUploadFrame' + id; //給iframe添加一個獨一無二的id
16 var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '">//創建iframe元素
17 if (window.ActiveXObject) {//判斷浏覽器是否支持ActiveX控件
18 if (typeof uri == 'boolean') {
19 iframeHtml += ' src="' + 'javascript:false' + '"';
20 } else if (typeof uri == 'string') {
21 iframeHtml += ' src="' + uri + '"';
22 }
23 }
24 iframeHtml += ' />';
25 jQuery(iframeHtml).appendTo(document.body); //將動態iframe追加到body中
26 return jQuery('#' + frameId).get(0); //返回iframe對象
27 },
28 createUploadForm: function (id, fileElementId, data) {//id為當前系統時間字符串,fileElementId為頁面<input type='file' />的id,data的值需要根據傳入json的鍵來決定
29 //create form
30 var formId = 'jUploadForm' + id; //給form添加一個獨一無二的id
31 var fileId = 'jUploadFile' + id; //給<input type='file' />添加一個獨一無二的id
32 var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //創建form元素
33 if (data) {//通常為false
34 for (var i in data) {
35 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根據data的內容,創建隱藏域,這部分我還不知道是什麼時候用到。估計是傳入json的時候,如果默認傳一些參數的話要用到。
36 }
37 } var oldElement = jQuery('#' + fileElementId); //得到頁面中的<input type='file' />對象
38 var newElement = jQuery(oldElement).clone(); //克隆頁面中的<input type='file' />對象
39 jQuery(oldElement).attr('id', fileId); //修改原對象的id
40 jQuery(oldElement).before(newElement); //在原對象前插入克隆對象
41 jQuery(oldElement).appendTo(form); //把原對象插入到動態form的結尾處
42 //set attributes
43 jQuery(form).css('position', 'absolute'); //給動態form添加樣式,使其浮動起來,
44 jQuery(form).css('top', '-1200px');
45 jQuery(form).css('left', '-1200px');
46 jQuery(form).appendTo('body'); //把動態form插入到body中
47 return form;
48 },
49 ajaxFileUpload: function (s) {//這裡s是個json對象,傳入一些ajax的參數
50 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
51 s = jQuery.extend({}, jQuery.ajaxSettings, s); //此時的s對象是由jQuery.ajaxSettings和原s對象擴展後的對象
52 var id = new Date().getTime(); //取當前系統時間,目的是得到一個獨一無二的數字
53 var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //創建動態form
54 var io = jQuery.createUploadIframe(id, s.secureuri); //創建動態iframe
55 var frameId = 'jUploadFrame' + id; //動態iframe的id
56 var formId = 'jUploadForm' + id; //動態form的id
57 // Watch for a new set of requests
58 if (s.global && !jQuery.active++) {//當jQuery開始一個ajax請求時發生
59 jQuery.event.trigger("ajaxStart"); //觸發ajaxStart方法
60 } var requestDone = false; //請求完成標志
61 // Create the request object
62 var xml = {}; if (s.global)
63 jQuery.event.trigger("ajaxSend", [xml, s]); //觸發ajaxSend方法
64 // Wait for a response to come back
65 var uploadCallback = function (isTimeout) {//回調函數
66 var io = document.getElementById(frameId); //得到iframe對象
67 try { if (io.contentWindow) {//動態iframe所在窗口對象是否存在
68 xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
69 xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
70 } else if (io.contentDocument) {//動態iframe的文檔對象是否存在
71 xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
72 xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
73 }
74 } catch (e) {
75 jQuery.handleError(s, xml, null, e);
76 } if (xml || isTimeout == "timeout") {//xml變量被賦值或者isTimeout == "timeout"都表示請求發出,並且有響應
77 requestDone = true; //請求完成
78 var status; try {
79 status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超時”,表示請求成功
80 // Make sure that the request was successful or notmodified
81 if (status != "error") { // process the data (runs the xml through httpData regardless of callback)
82 var data = jQuery.uploadHttpData(xml, s.dataType); //根據傳送的type類型,返回json對象,此時返回的data就是後台操作後的返回結果
83 // If a local callback was specified, fire it and pass it the data
84 if (s.success)
85 s.success(data, status); //執行上傳成功的操作
86 // Fire the global callback
87 if (s.global)
88 jQuery.event.trigger("ajaxSuccess", [xml, s]);
89 } else
90 jQuery.handleError(s, xml, status);
91 } catch (e) {
92 status = "error";
93 jQuery.handleError(s, xml, status, e);
94 } // The request was completed
95 if (s.global)
96 jQuery.event.trigger("ajaxComplete", [xml, s]); // Handle the global AJAX counter
97 if (s.global && ! --jQuery.active)
98 jQuery.event.trigger("ajaxStop"); // Process result
99 if (s.complete)
100 s.complete(xml, status);
101 jQuery(io).unbind();//移除iframe的事件處理程序
102 setTimeout(function () {//設置超時時間
103 try {
104 jQuery(io).remove();//移除動態iframe
105 jQuery(form).remove();//移除動態form
106 } catch (e) {
107 jQuery.handleError(s, xml, null, e);
108 }
109 }, 100)
110 xml = null
111 }
112 } // Timeout checker
113 if (s.timeout > 0) {//超時檢測
114 setTimeout(function () { // Check to see if the request is still happening
115 if (!requestDone) uploadCallback("timeout");//如果請求仍未完成,就發送超時信號
116 }, s.timeout);
117 } try { var form = jQuery('#' + formId);
118 jQuery(form).attr('action', s.url);//傳入的ajax頁面導向url
119 jQuery(form).attr('method', 'POST');//設置提交表單方式
120 jQuery(form).attr('target', frameId);//返回的目標iframe,就是創建的動態iframe
121 if (form.encoding) {//選擇編碼方式
122 jQuery(form).attr('encoding', 'multipart/form-data');
123 } else {
124 jQuery(form).attr('enctype', 'multipart/form-data');
125 }
126 jQuery(form).submit();//提交form表單
127 } catch (e) {
128 jQuery.handleError(s, xml, null, e);
129 }
130 jQuery('#' + frameId).load(uploadCallback); //ajax 請求從服務器加載數據,同時傳入回調函數
131 return { abort: function () { } };
132 },
133 uploadHttpData: function (r, type) { var data = !type;
134 data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context
135 if (type == "script")
136 jQuery.globalEval(data); // Get the JavaScript object, if JSON is used.
137 if (type == "json")
138 eval("data = " + data); // evaluate scripts within html
139 if (type == "html")
140 jQuery("<div>").html(data).evalScripts(); return data;
141 }
142 })
3。php代碼
1 <?php
2 //print_r($_FILES);
3 //echo json_encode(print_r($_FILES));
4
5 /**
6 * 生成唯一字符串
7 * @return string
8 */
9 function getUniName(){
10 return md5(uniqid(microtime(true),true));
11 }
12
13 /**
14 * 得到文件的擴展名
15 * @param string $filename
16 * @return string
17 */
18 function getExt($filename){
19 return strtolower(end(explode(".",$filename)));
20 }
21
22 /**
23 * 構建上傳文件信息
24 * @return array
25 */
26
27 function buildInfo(){
28 if(!$_FILES){
29 return ;
30 }
31 $i=0;
32 foreach($_FILES as $v){
33 //單文件
34 if(is_string($v['name'])){
35 $files[$i]=$v;
36 $i++;
37 }else{
38 //多文件
39 foreach($v['name'] as $key=>$val){
40 $files[$i]['name']=$val;
41 $files[$i]['size']=$v['size'][$key];
42 $files[$i]['tmp_name']=$v['tmp_name'][$key];
43 $files[$i]['error']=$v['error'][$key];
44 $files[$i]['type']=$v['type'][$key];
45 $i++;
46 }
47 }
48 }
49 return $files;
50 }
51 function uploadFile($path="uploads",$allowExt=array("gif","jpeg","png","jpg","wbmp"),$maxSize=2097152,$imgFlag=true){
52 if(!file_exists($path)){//判斷是否有$path文件夾,沒有則創建
53 mkdir($path,0777,true);//0777表示最大權限
54 }
55 $i=0;
56 $files=buildInfo();
57 if(!($files&&is_array($files))){
58 return ;
59 }
60 foreach($files as $file){
61 if($file['error']===UPLOAD_ERR_OK){//就是0
62 $ext=getExt($file['name']);
63 //檢測文件的擴展名
64 if(!in_array($ext,$allowExt)){
65 exit("非法文件類型");
66 }
67 //校驗是否是一個真正的圖片類型
68 if($imgFlag){
69 if(!getimagesize($file['tmp_name'])){
70 exit("不是真正的圖片類型");
71
72 }else{
73 $file["filesize"]=getimagesize($file['tmp_name']);
74 //把文件信息付給$file 傳到前台返回時數組
75 //如 [720, 1280, 2, "width="720" height="1280"", 8, 3, "image/jpeg"]
76 }
77 }
78 //上傳文件的大小
79 if($file['size']>$maxSize){
80 exit("上傳文件過大");
81 }
82 if(!is_uploaded_file($file['tmp_name'])){
83 exit("不是通過HTTP POST方式上傳上來的");
84 }
85 $filename=getUniName().".".$ext;//改文件重新命名
86 $destination=$path."/".$filename;
87 if(move_uploaded_file($file['tmp_name'], $destination)){
88 $file['name']=$filename;
89 $file['path_name']=$destination;
90 unset($file['tmp_name'],$file['size'],$file['type']);//去除不需要傳給的信息
91 $uploadedFiles[$i]=$file;
92 $i++;
93 }
94 }else{
95 switch($file['error']){
96 case 1:
97 $mes="超過了配置文件上傳文件的大小";//UPLOAD_ERR_INI_SIZE
98 break;
99 case 2:
100 $mes="超過了表單設置上傳文件的大小"; //UPLOAD_ERR_FORM_SIZE
101 break;
102 case 3:
103 $mes="文件部分被上傳";//UPLOAD_ERR_PARTIAL
104 break;
105 case 4:
106 $mes="沒有文件被上傳1111";//UPLOAD_ERR_NO_FILE
107 break;
108 case 6:
109 $mes="沒有找到臨時目錄";//UPLOAD_ERR_NO_TMP_DIR
110 break;
111 case 7:
112 $mes="文件不可寫";//UPLOAD_ERR_CANT_WRITE;
113 break;
114 case 8:
115 $mes="由於PHP的擴展程序中斷了文件上傳";//UPLOAD_ERR_EXTENSION
116 break;
117 }
118 echo $mes;
119 }
120 }
121 return $uploadedFiles;
122 };
123
124 $rows=uploadFile($path="uploads",$allowExt=array("gif","jpeg","png","jpg","wbmp"),$maxSize=2097152,$imgFlag=true);
125
126 echo json_encode($rows);
uploadFile($path="uploads",$allowExt=array("gif","jpeg","png","jpg","wbmp"),$maxSize=2097152,$imgFlag=true);
這段php代碼可以更改的可以上傳其他文件和大小限制。getimagesize是判斷是否為病毒文件更改後綴。
上述代碼直接復制即可完成圖片和用戶數據的同時上傳。
返回結果:[{"name":"d032a4ee7e957d956c8af0039d7e3085.jpg","error":0,"filesiz":{"0":720,"1":1280,"2":2,"3":"width=\"720\" height=\"1280\"","bits":8,"channels":3,"mime":"image\/jpeg"},"path_name":"uploads\/d032a4ee7e957d956c8af0039d7e3085.jpg"}]