在ajax還沒有流行起來(lái)的時(shí)候,因?yàn)楸韱问褂胒orm的action進(jìn)行頁(yè)面跳轉(zhuǎn)提交,所以不存在什么問題。
自從ajax流行起來(lái)之后,一般的表單都是通過ajax方式提交,所以碰到帶文件上傳的表單就比較麻煩。后來(lái)在網(wǎng)上查了一下,基本都沒有比較好的解決辦法,所以還是對(duì)這種特殊的表單使用頁(yè)面跳轉(zhuǎn)方式提交。最近看到同事用一種偽ajax方式解決了此問題。其基本原理就是在頁(yè)面增加一個(gè)隱藏iframe,然后通過ajax提交除文件之外的表單數(shù)據(jù),在表單數(shù)據(jù)提交成功之后的回調(diào)函數(shù)中,通過form單獨(dú)提交文件,而這個(gè)提交文件的form的target就指向前述隱藏的iframe。代碼如下(注意form的target屬性指向隱藏的iframe):
<form style="padding:0px;margin:0px;" target="upload" action="/xxx/xx.do" id="uploadForm" name="uploadForm" encType="multipart/form-data" method="post">
<input type="file" id=""attachFile/>
</form>
<iframe name="upload" style="display:none"></iframe>
<input type="file" id=""attachFile/>
</form>
<iframe name="upload" style="display:none"></iframe>
上述偽ajax方法的缺點(diǎn)是,表單數(shù)據(jù)和文件數(shù)據(jù)不能做到一個(gè)事物里面,如果后面文件上傳失敗(比如網(wǎng)絡(luò)中斷、服務(wù)器down掉等),則前面上傳的表單數(shù)據(jù)算是垃圾數(shù)據(jù)了。當(dāng)然這個(gè)在對(duì)數(shù)據(jù)一致性要求不是很高的環(huán)境,還是不錯(cuò)的解決辦法。