form.enctype 屬性指定表單提交時的數據編碼方式,直接影響文件上傳、表單數據格式。常用值:
application/x-www-form-urlencoded(默認):鍵值對編碼,不支持文件。multipart/form-data:文件上傳必須,二進制分段編碼。text/plain:純文本,調試用,極少用於生產。<form id="frm1" enctype="text/plain">
First name: <input name="fname" value="Donald"><br>
Last name: <input name="lname" value="Duck"><br>
</form>
<script>
console.log(document.getElementById('frm1').enctype); // "text/plain"
</script>
const form = document.getElementById('uploadForm');
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', () => {
if (fileInput.files.length > 0) {
form.enctype = 'multipart/form-data'; // 必須設置
} else {
form.enctype = 'application/x-www-form-urlencoded';
}
});
enctype 僅在 method="post" 時生效。multipart/form-data 後,瀏覽器自動生成 boundary 分隔符,無需手動處理。$.ajax 上傳文件時需 processData: false, contentType: false,由瀏覽器自動設置正確 Content-Type(含 boundary)。通過 form.enctype 讀寫表單編碼類型,配合 method="post" 實現文件上傳。現代開發多用 FormData + fetch,瀏覽器自動處理編碼,無需手動操作 enctype。