採用 隱藏 Iframe 實現無刷新上傳體驗:父頁面放置輸入框與 Iframe,Iframe 內載入上傳介面,上傳成功後透過 parent.document.getElementById() 回寫檔名至父頁面表單欄位。
<!-- 大圖欄位 --> <input type="text" name="bigImageURL" id="bigImageURL" value="" /> <iframe src="uppic.php?id=bigImageURL" width="600" height="25" frameborder="0" scrolling="no"></iframe> <!-- 小圖欄位 --> <input type="text" name="smallImageURL" id="smallImageURL" value="" /> <iframe src="uppic.php?id=smallImageURL" width="600" height="25" frameborder="0" scrolling="no"></iframe>
關鍵:iframe src 參數 id=欄位ID,上傳腳本據此決定回寫目標。
<?php
header("Content-Type: text/html; charset=GB2312");
$id = $_GET['id'] ?? ''; // 目標表單欄位 ID
switch ($_GET['action'] ?? '') {
case 'up': uploadFile($id); break;
default: showUploadForm($id); break;
}
function showUploadForm($id) {
?>
<!DOCTYPE html>
<html><head><title>圖片上傳</title>
<style>input{border:1px solid #bdbcbd;padding:3px 5px;}.btn{padding:3px 10px;border:1px solid #bdbcbd;background:#fff;cursor:pointer;}</style>
</head><body style="font-size:12px;margin:0;padding:0">
<form action="uppic.php?action=up&id== urlencode($id) ?>" enctype="multipart/form-data" method="post" onsubmit="return checkFile()">
<input name="strPhoto" type="file" id="strPhoto" size="40" />
<input type="submit" name="Submit" value="上 傳" class="btn" />
</form>
<script>
function checkFile() {
var f = document.forms[0].strPhoto.value;
if (!f) { alert("請選擇檔案"); return false; }
return true;
}
</script>
</body></html>
<?php
}
function uploadFile($id) {
$saveDir = __DIR__ . '/uploads/'; // 需可寫入
if (!is_dir($saveDir)) mkdir($saveDir, 0755, true);
if (empty($_FILES['strPhoto']['name'])) {
echoMsg("請選擇檔案");
return;
}
$ext = strtolower(pathinfo($_FILES['strPhoto']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, ['jpg','jpeg','gif','png','bmp'])) {
echoMsg("格式錯誤,僅允許 jpg/gif/png/bmp");
return;
}
$newName = date('YmdHis') . '.' . $ext;
$dest = $saveDir . $newName;
if (move_uploaded_file($_FILES['strPhoto']['tmp_name'], $dest)) {
// 成功:回寫父頁面表單欄位
echo "<span style='color:red;line-height:25px'>上傳成功</span>";
echo "<script>parent.document.getElementById('{$id}').value='{$newName}';</script>";
echo "<a href='#' onclick='history.go(-1)'>重新上傳</a>";
} else {
echoMsg("上傳失敗,請重試");
}
}
function echoMsg($msg) {
echo "<span style='color:red;line-height:25px'>{$msg} <a href='#' onclick='history.go(-1)'>返回</a></span>";
}
progress 事件顯示進度條