表單 target 指向隱藏的 <iframe>,提交後由 iframe 載入後端回傳的 JavaScript 呼叫父頁面函數更新狀態。
<html>
<head>
<title>無刷新上傳</title>
<meta charset="utf-8">
<script>
function startUpload() {
document.getElementById('processing').innerHTML = '上傳中...';
return true;
}
function stopUpload(result) {
var msg = ['上傳成功', '檔案超過限制', '只能上傳圖片', '上傳失敗'];
document.getElementById('processing').innerHTML = msg[result] || msg[3];
}
</script>
</head>
<body>
<div style="text-align:center">
<div id="processing"></div>
<form action="upload.php" method="post" enctype="multipart/form-data" target="form-target" onsubmit="return startUpload()">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input type="file" name="myfile" />
<input type="submit" name="sub" value="upload" />
</form>
<iframe name="form-target" style="width:0;height:0;border:0;"></iframe>
</div>
</body>
</html>
$maxSize) {
$result = 1;
} elseif (!in_array($ext, $allowed)) {
$result = 2;
} elseif (is_uploaded_file($file['tmp_name'])) {
$dest = $uploadDir . '/' . $file['name'];
if (@move_uploaded_file($file['tmp_name'], $dest)) {
$result = 0;
}
} else {
$result = 3;
}
}
?>
<script>
window.top.window.stopUpload(= $result ?>);
</script>
FormData + XMLHttpRequest/fetch。