文章詳情頁
ajax使用formdata上傳文件流
瀏覽:163日期:2022-06-11 18:05:20
今天在做項目的時候涉及到了ajax上傳文件流的問題,由于是移動端兩個頁面的兩個表單使用同一個ajax地址進行上傳數(shù)據(jù)給后臺,數(shù)據(jù)中涉及到了不同類型的input,其中存在了file類型的input,導(dǎo)致無法使用表單序列化直接傳輸數(shù)據(jù)。
只存在傳遞一般的參數(shù)時,可以使用$("#表單id").serialize()對form表單序列化,從而將form表單中的所有參數(shù)傳遞到服務(wù)端。而上傳文件的文件流時無法被序列化并傳遞的,因此使用了FormData的對象進行文件上傳。具體formdata的使用可以參見:官網(wǎng)
//html如下 //form1 <form id="registerForm" method="post" action=""> <div> <div> <i></i> </div> <div> <input type="text" placeholder="店鋪名稱" id="shopName" name="shopName"> </div> </div> <div> <div> <i></i> </div> <div> <input type="text" placeholder="本人姓名" id="name" name="name"> </div> </div> </form> //form2 <form action="" method="post" id="registerForm2"> <input id="frontPhoto" name="frontPhoto"/> <input id="backPhoto" name="backPhoto"/> <input id="handlePhoto" name="handlePhoto"/> </form>
$("#btn-register-confirm").click(function () { //upRegister()是表單驗證,這就沒有給出了 if (upRegister()){ var form=$("#registerForm2")[0];//第二個表單的id,注意[0]不能漏掉 var fd=new FormData(form); //由于后臺接收的數(shù)據(jù)只能是序列化之后的樣子,所以將第一個表單的字段存放在cookie中。通過fd.append()以鍵值對形式存放 fd.append("shopName",$.cookie("shopName")); fd.append("name",$.cookie("name")); $.ajax({ type:"post", async: false, url:"url", data:fd, processData:false,//因為data值是FormData對象,不需要對數(shù)據(jù)做處理。 contentType:false,//因為是由<form>表單構(gòu)造的FormData對象,所以這里設(shè)置為false。 success:function(data){ if (data.resultCode=="0"){ webToast("成功注冊!"); console.log("成功注冊"); } }, error:function(){ console.log("注冊失敗"); } }) } });
以上就實現(xiàn)了ajax上傳文件流及一般參數(shù)。這主要涉及到2方面:
- 不同頁面的不同表單要放在同一個按鈕觸發(fā)同一個ajax傳輸?shù)椒?wù)器,使用cookie先存儲一個表單數(shù)據(jù),這可能會麻煩些并且不安全,但目前我也只想到了這種方式,如果有更好的歡迎補充;
- ajax上傳文件流,要注意var fd=new FormData($("#表單id")[0]);[0]千萬要帶上,我就是因為這個弄了一整天才好。processData:false, contentType:false,還有ajax的這兩個參數(shù)要寫為false,具體原因上面已經(jīng)寫了。
更多精彩內(nèi)容請參考專題《ajax上傳技術(shù)匯總》,《javascript文件上傳操作匯總》和《jQuery上傳操作匯總》進行學(xué)習(xí)。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持。
標(biāo)簽:
Ajax
相關(guān)文章:
1. 使用FormData進行Ajax請求上傳文件的實例代碼2. Ajax實現(xiàn)表格中信息不刷新頁面進行更新數(shù)據(jù)3. ajax請求后臺得到j(luò)son數(shù)據(jù)后動態(tài)生成樹形下拉框的方法4. Ajax請求超時與網(wǎng)絡(luò)異常處理圖文詳解5. Ajax返回值類型與用法實例分析6. laravel ajax curd 搜索登錄判斷功能的實現(xiàn)7. axios和ajax的區(qū)別點總結(jié)8. 爬取今日頭條Ajax請求9. 關(guān)于Ajax跨域問題及解決方案詳析10. Ajax引擎 ajax請求步驟詳細代碼
排行榜
