ajaxfileupload.js結合input[type=file]無重新整理上傳,ajaxfileupload.js

來源:互聯網
上載者:User

ajaxfileupload.js結合input[type=file]無重新整理上傳,ajaxfileupload.js

jQuery外掛程式AjaxFileUpload用來實現ajax檔案上傳,該外掛程式使用非常簡單,接下來寫個demo示範怎麼用AjaxFileUpload外掛程式實現檔案上傳。

說明:

文法:$.ajaxFileUpload([options])

  options參數說明:

1、url            上傳處理常式地址。  
2,fileElementId       需要上傳的檔案域的ID,即<input type="file">的ID。
3,secureuri        是否啟用安全提交,預設為false。 
4,dataType        伺服器返回的資料類型。可以為xml,script,json,html。如果不填寫,jQuery會自動判斷。
5,success        提交成功後自動執行的處理函數,參數data就是伺服器返回的資料。
6,error          提交失敗自動執行的處理函數。
7,data           自訂參數。這個東西比較有用,當有資料是與上傳的圖片相關的時候,這個東西就要用到了。
8, type            當要提交自訂參數時,這個參數要設定成post

錯誤提示:

1,SyntaxError: missing ; before statement錯誤
  如果出現這個錯誤就需要檢查url路徑是否可以訪問
2,SyntaxError: syntax error錯誤
  如果出現這個錯誤就需要檢查處理提交操作的伺服器幕後處理程式是否存在語法錯誤
3,SyntaxError: invalid property id錯誤
  如果出現這個錯誤就需要檢查文本域屬性ID是否存在
4,SyntaxError: missing } in XML expression錯誤
  如果出現這個錯誤就需要檢查檔案name是否一致或不存在
5,其它自訂錯誤
  大家可使用變數$error直接列印的方法檢查各參數是否正確,比起上面這些無效的錯誤提示還是方便很多。


1、引入其支援檔案,注意引用順序

<script type="text/javascript" src="<%=basePath%>js/jquery-1.8.0.min.js"></script><script type="text/javascript" src="<%=basePath%>js/ajaxfileupload.js"></script>

2、在版面設定檔案選擇框,無需form包裹:注意此處id和name必須設定,在文章中你將知道原因,在此不做詳細解釋。

<input type="file" id="fileUpload" name="fileUploa" />

3、實現上傳功能

<script type="text/javascript">    //初始化頁面$(document).ready(function(e) {
 //選擇檔案框選擇檔案change事件 $("#fileUpload").change(function(){ var url=$(this).val(); var extend=url.substring(url.indexOf(".")+1); var ext=new Array("jpg","jpeg","png","gif","bmp"); if(ext.toString().indexOf(extend)==-1){ alert("您上傳的格式不正確,僅支援jpg、jpeg、png、gif、bmp,請重新選擇!"); }  $.ajaxFileUpload({        url: '<%=basePath%>attach/api/upload', //後台提交地址        secureuri: false,//非同步        fileElementId: 'fileUpload',//上傳控制項ID        dataType: 'json',//返回的資料資訊格式        type:"post", //如果帶附加參數,請設定type        success: function(data, status) {            if (data.success ==true) {               var attach=data.result[0];               $("[name=photo]").attr("src",attach.filePath);               alert("上傳成功");             } else {                alert("伺服器故障,稍後再試!");            }        }, error: function(data, status, e) {           alert(e);        }    });});});</script>
4、後台介面:此處採用spring MVC

@RequestMapping(value = "/upload", method ={RequestMethod.POST,RequestMethod.GET})@ResponseBodypublic HashMap<String,Object> upload(HttpServletRequest request, HttpServletResponse response) 
                                                    throws InstantiationException, IllegalAccessException{HashMap<String,Object> result=new HashMap<String,Object>();ArrayList<Attach> attachList=attachService.uploadfy(request);if(attachList.size()>0){result.put("success", true);result.put("result", attachList);}else{result.put("success", false);}    return result;}
5、實現以上步奏即可完成上傳。

總結:

在使用過程中可能遇到如下問題:

1、上傳報該異常:SyntaxError:Unexpected token <

     原因:是因為Server端的Response上加上了contentType="application/json"。但有時後端這麼做是必須的,所以修改ajaxFileUpload源碼,將<pre></pre>標籤去掉,如下: (請參考:http://liwx2000.iteye.com/blog/1540321)

uploadHttpData: function( r, type ) {          var data = !type;          data = type == "xml" || data ? r.responseXML : r.responseText;          // If the type is "script", eval it in global context          if ( type == "script" )              jQuery.globalEval( data );          // Get the JavaScript object, if JSON is used.          if ( type == "json" ) {               ////////////以下為新增代碼///////////////               data = r.responseText;               var start = data.indexOf(">");               if(start != -1) {                 var end = data.indexOf("<", start + 1);                 if(end != -1) {                   data = data.substring(start + 1, end);                  }               }                ///////////以上為新增代碼///////////////                eval( "data = " + data);          }          // evaluate scripts within html          if ( type == "html" )              jQuery("<div>").html(data).evalScripts();            return data;      }  

2、使用<input type="file" id="fileUpload" />該方式,在後台接收不到值?
      原因:需要設定一下name屬性    <input type="file" id="fileUpload" name="名稱任意" />

   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.