使用ajaxfileupload.js實現上傳文件功能
一、ajaxFileUpload是一個異步上傳文件的jQuery插語法:$.ajaxFileUpload([options])
options參數說明:
1、url 上傳處理程序地址
2、fileElementId 文件選擇框的id屬性,即的id
3、secureuri 是否啟用安全提交,默認為false
4、dataType 服務器返回的數據類型。可以為xml,script,json,html。如果不填寫,jQuery會自動判斷
5、success 服務器響應成功后的處理函數 ,參數data就是服務器返回的數據
6、error 服務器響應失敗后的處理函數
7、data 自定義參數,當有數據要和上傳的文件一起傳到后臺處理的時候會用到。這里注意,數據格式比較嚴格{param:[{‘param1':'value1','param2':'value2' },{‘param1':'value3','param2':'value4' }]}, 其中單引號不能改為雙引號
8、type 提交數據的方式,一般為post
二、使用方法
第一步、先引入jquery和ajaxFileUpload插件,注意先后順序:
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script> <script type= "text/javascript" src= "js/ajaxfileupload.js" ></script>
第二步、html代碼
原始的,控件展示效果如下:
因為原始控件的樣式無法改變,所以我們一般會讓這個標簽隱藏,然后點擊別的標簽來觸發上傳控件。
<input type ="file" id="ImportPicInput" name= "myfile" style=" display: none" /> <div class ="input-append"> <label for ="importPicName"> 上傳原始圖片:</label > <input type ="text" class="input-large" id= "importPicName" /> <a class ="btn btn-default" onclick= "$('#ImportPicInput').click();" > 打開</a> </div > 展現的頁面效果:
第三步、js代碼
在用戶選擇完上傳圖片后,需要把圖片名稱顯示到輸入框中,還需要在js文件中加入代碼:
$(document).ready(function(e) { $('body').on('change',$('#ImportPicInput'),function(){ $( "#importPicName").val($( "#ImportPicInput").val()); }); }); 上傳文件的js代碼:
$.ajaxFileUpload({ type: "POST", url: "/toolkit/importPicFile.do", data:{picParams:text},//要傳到后臺的參數,沒有可以不寫 secureuri : false,//是否啟用安全提交,默認為false fileElementId:'ImportPicInput',//文件選擇框的id屬性 dataType: 'json',//服務器返回的格式 async : false, success: function(data){ if(data.result=='success'){ //coding }else{ //coding } }, error: function (data, status, e){ /coding } });
新聞熱點
疑難解答
圖片精選