萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> 動態設置上傳文件的enctype

動態設置上傳文件的enctype

動態設置上傳文件的enctype


<fm id="up" name="up" action="upfileile.php" method="post" enctype="multipart/fm-data">
<input type="file" name="upfileilefile[]" />
<input type="file" name="upfileilefile[]" />
<button type="submit" >upfileile</button>
</fm>
學過js的人可能試圖用js檢查並控制enctype得類型

fm=document.getElementById('up');
if(fm.getAttribute('enctype')!='multipart/fm-data'){
    fm.setAttribute('enctype','multipart/fm-data');
}以上代碼完全按照W3C格式
FF下運行良好 但是IE不兼容,其它浏覽器可以不兼容,就IE不能不兼容
在看YUI類庫時得到啟發
IE中fm沒有enctype屬性,只有encoding屬性,那麼以上代碼改寫為:

fm=document.getElementById('up');
if(fm.getAttribute('enctype')!='multipart/fm-data'&&fm.encoding!='multipart/fm-data')
  if(fm.encoding){
      fm.setAttribute('encoding','multipart/fm-data');
  }else{
      fm.setAttribute('enctype','multipart/fm-data');
  }
}
//最外成if判斷可以去掉 因為你是要設置它可以上傳文件這樣你可以試試這樣得代碼了
<script type="text/javascript">
function upfileile(fm){
  if(fm.encoding){
      fm.setAttribute('encoding','multipart/fm-data');
  }else{
      fm.setAttribute('enctype','multipart/fm-data');
  }
  fm.setAttribute('method',post');
  if(!fm.getAttribue('action')){
      fm.setAttribute('action',location.href);
  }
  fm.submit();
}
</script>
<fm action="upfileile.php" onsubmit="try{upfileile(this);}catch(e){};return false;">
<input type="file" name="upfileilefile[]" />
<input type="file" name="upfileilefile[]" />
<button type="submit" >upfileile</button>
</fm>

copyright © 萬盛學電腦網 all rights reserved