做軟工作業(yè)時,需要實現(xiàn)無刷新異步上傳圖片到服務(wù)器,于是想利用Ajax:
得到file的val,再post過去…
等真正實現(xiàn)的時候才發(fā)現(xiàn),根本行不通。
于是翻來翻去找到一個封裝好的js插件,可以實現(xiàn)異步上傳文件。
AjaxFileUpload
這個插件的原理是創(chuàng)建隱藏的表單和iframe,然后用JS去提交,獲得返回值。
語法
$.ajaxFileUpload([options])
參數(shù)說明
url 上傳處理程序地址。
fileElementId 需要上傳的文件域的ID,即的ID。
secureuri 是否啟用安全提交,默認(rèn)為false。
dataType 服務(wù)器返回的數(shù)據(jù)類型。可以為xml,script,json,html。如果不填寫,jQuery會自動判斷。
success 提交成功后自動執(zhí)行的處理函數(shù),參數(shù)data就是服務(wù)器返回的數(shù)據(jù)。
error 提交失敗自動執(zhí)行的處理函數(shù)。
data 自定義參數(shù)。這個東西比較有用,當(dāng)有數(shù)據(jù)是與上傳的圖片相關(guān)的時候,這個東西就要用到了。
type 當(dāng)要提交自定義參數(shù)時,這個參數(shù)要設(shè)置成post
使用方法
引入jQuery與ajaxFileUpload插件(由api中心強力提供)
<script type="text/javascript" src="https://api.mayuko.cn/js/jquery.min.js"></script><script type="text/javascript" src="https://api.mayuko.cn/js/ajaxfileupload.js"></script>
擴展HTML代碼
<td height="52" class="inputContent" ><div align="center">附件1<input type="file" name="upload_file" id="ss_upload_file1"></td><td colspan="3"><input type="button" name="Submit3" value="上 傳" class="button" id="ss_file_upload"></td>
JS代碼
$("#ss_file_upload").click(function(){ $.ajaxFileUpload({ url:'doajaxfileupload.php',//請求地址 secureuri:false,//是否需要安全協(xié)議 fileElementId:'ss_upload_file1',//file的ID dataType: 'text',//返回值類型,一般為json success: function(img_data1)//成功后執(zhí)行 { $(ss_file1_url).attr("value",img_data1); alert("上傳成功"); }, error:function(img_data1,status,e){ alert("上傳失敗"); } })})
PHP代碼
后臺就是進行上傳操作啦,因為是課程設(shè)計所以我將圖片上傳到了七牛云存儲中。
如何上傳到七牛中?
<?php//echo var_dump($_FILES);//echo $_FILES['upload_file']['tmp_name'];$file_infor = array("status"=>'',"url"=>'');require_once("qiniu/io.php");require_once("qiniu/rs.php");$bucket = "";//你的bucket$key1 = $_FILES["upload_file"]["name"] ;$accessKey = '';//AK$secretKey = '';//SKQiniu_SetKeys($accessKey, $secretKey);$putPolicy = new Qiniu_RS_PutPolicy($bucket);$upToken = $putPolicy->Token(null);$putExtra = new Qiniu_PutExtra();$putExtra->Crc32 = 1;list($ret, $err) = Qiniu_PutFile($upToken, $key1,$_FILES["upload_file"]["tmp_name"], $putExtra);$url='bucket域名'.$key1;if ($_FILES["upload_file"]["error"] > 0){$file_infor["status"] = 'error';}else{$file_infor["status"] = 'success';$file_infor["url"] = $url;}echo $url;?>
$_FILES是一個數(shù)組:
array (‘upload_file' =>array (‘name' => ‘733626970332872971.jpg',‘type' => ‘image/jpeg',‘tmp_name' => ‘C://Windows//Temp//phpF203.tmp',‘error' => 0,‘size' => 210744,),)
這樣前臺就可以接收到上傳圖片之后的url值并進行顯示操作了。
一般來說,AjaxFileUpload的返回類型是json格式,可是在測試的時候前臺一直無法解析json數(shù)據(jù),所以無解之后就換成text數(shù)據(jù)了。
錯誤提示
1.Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method ‘handleError'
這是因為高版本的jQuery中取消了handleError方法,在ajaxfileupload.js中加入該方法就可以啦。 ;)
handleError: function( s, xhr, status, e ) {// If a local callback was specified, fire itif ( s.error ) {s.error.call( s.context || s, xhr, status, e );}// Fire the global callbackif ( s.global ) {(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );}}
2.success: function(data)中data為空值
應(yīng)該是json數(shù)據(jù)的問題,我的解決方法是設(shè)置返回數(shù)據(jù)的類型是 text,用alert(data +”:” + data.length); 觀察返回的數(shù)據(jù)是否有效。
3.一直跳轉(zhuǎn)到error方法中
當(dāng)執(zhí)行if(type==”json”) eval(“data = “+data);會拋出異常,導(dǎo)致在處理異常的時候?qū)tatus = “error” 因此一直執(zhí)行error方法。
將ajaxfileupload.js中uploadHttpData: function( r, type ) 方法的 eval(“data = “+data+” “)改為 eval(“data = /” “+data+” /” “);
4.SyntaxError: syntax error錯誤
檢查處理提交操作的服務(wù)器后臺處理程序是否存在語法錯誤。
5.change第二次失效
綁定change事件,實現(xiàn)選擇圖片后自動上傳,但是觸發(fā)一次change事件后,下次就不會再觸發(fā)change事件。
原因:由于ajaxFileUpload把原來的file元素替換成新的file元素,所以之前綁定的change事件就失效了。
解決方法:在 $.ajaxFileUpload({option})中的回調(diào)函數(shù)里 重新綁定change事件。
$("#upload_file").change(function(){ UploadImg();});UploadImg = function() { $(window).bind('beforeunload',function(){return '正在上傳,確定離開此頁面嗎?';}); $('#loading').attr('style','display:block;') $.ajaxFileUpload({ url:'upload_ajax.php', secureuri:false, fileElementId:'upload_file', dataType: 'text', success: function(data) { $('#loading').attr('style','display:none;'); if(data == 0){ $("body").overhang({ type: "error", message: "上傳失敗,CODE:00020" }); } else if(data == 1){ $("body").overhang({ type: "success", message: "上傳成功!" }); setTimeout(function(){ window.location.reload(); },1000); } else{ $("body").overhang({ type: "error", message: "格式錯誤,僅支持jpg,png,gif" }); } $(window).unbind('beforeunload'); $("#upload_file").change(function () { UploadImg(); }); }, error:function(data,status,e){ $("body").overhang({ type: "error", message: "上傳失敗,CODE:00031" }); } }) }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點
疑難解答
圖片精選