本文示範透過 iframe 實現無刷新上傳,上傳成功後以 JavaScript 將檔案名回填至父頁面指定的輸入欄位。
<!-- 大圖上傳 -->
<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'];
switch ($_GET['action']) {
case 'up':
uploadImage($id);
break;
default:
showUploadForm($id);
}
function showUploadForm($id) {
?>
<form action="uppic.php?action=up&id=<?=$id?>" enctype="multipart/form-data" method="post" onsubmit="return check()">
<script>
function check() {
var file = document.form.strPhoto.value;
if (!file) { alert('請選擇檔案'); return false; }
return true;
}
</script>
<input name="strPhoto" type="file" id="strPhoto" size="40">
<input type="submit" value="上傳" class="inputbut">
</form>
<?php
}
function uploadImage($id) {
global $web_picdir;
$savePath = dirname(__FILE__) . '/' . $web_picdir;
$fileName = date('YmdHis') . '.' . pathinfo($_FILES['strPhoto']['name'], PATHINFO_EXTENSION);
// 檢查副檔名
$allowed = ['jpg','gif','bmp','png'];
$ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
echo '格式錯誤'; exit;
}
if (move_uploaded_file($_FILES['strPhoto']['tmp_name'], $savePath . $fileName)) {
echo '上傳成功<script>parent.document.getElementById("' . $id . '").value="' . $fileName . '"</script>';
} else {
echo '上傳失敗';
}
}
?>
move_uploaded_file 替代 copy,確保上傳檔案合法性