ASP.NET FileUpload 控制項在 IE 中 value 屬性為唯讀,無法直接用 JavaScript 清空。若在伺服端判斷不儲存,檔案仍會被上傳浪費頻寬。
<script type="text/javascript">
function clearFileInput(file)
{
var form = document.createElement('form');
document.body.appendChild(form);
var pos = file.nextSibling; // 記住原位置
form.appendChild(file); // 移入暫存 form
form.reset(); // 重置,清空 value
pos.parentNode.insertBefore(file, pos); // 移回原位
document.body.removeChild(form);
}
</script>
btnCancel.OnClientClick = "clearFileInput(document.getElementById('" + FileUpload1.ClientID + "'));";
此技巧不需將暫存 Form 加入 DOM 樹即可運作,零介面干擾,完美解決 IE 下 FileUpload 唯讀難題。