早期 AJAX 上傳需手動構造 multipart/form-data 請求體,現代建議用 FormData + fetch/axios。本文保留原始手動構造版本供教學參考,並提供現代寫法對照。
project/
├── index.html # 前端頁面
└── upload.php # 後端處理
index.html (原始手動構造版)<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>AJAX 上傳示例</title></head><body>
<h1>Ajax file upload sample</h1>
<input type="button" id="btn_send" value="上傳測試">
<div id="result"></div>
<script>
// 手動構造 multipart/form-data (僅教學用,生產請用 FormData)
document.getElementById('btn_send').onclick = function() {
var boundary = '-------7d8d733180846';
var data = '';
data += '--' + boundary + '\r\n';
data += 'Content-Disposition: form-data; name="photofile"; filename="a.txt"\r\n';
data += 'Content-Type: text/plain\r\n\r\n';
var text = 'My name is Wilson Lin.';
data += text + '\r\n';
data += '--' + boundary + '--\r\n';
var xhr = new XMLHttpRequest(); // 現代瀏覽器通用
xhr.open('POST', './upload.php', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('Content-Length', data.length);
xhr.onload = function() {
document.getElementById('result').innerHTML = xhr.responseText;
};
xhr.send(data);
};
</script>
</body></html>
upload.php<?php
// 簡單演示:直接複製暫存檔到 D:/ (Windows 路徑,Linux 請改)
$uploadDir = 'D:/'; // 請確保目錄存在且可寫
$name = basename($_FILES['photofile']['name']);
$target = $uploadDir . $name;
if (move_uploaded_file($_FILES['photofile']['tmp_name'], $target)) {
echo "URL: <a href='https://localhost/$name' target='_blank'>$name</a><br/>";
echo "Upload successed!";
} else {
echo "Upload failed: " . $_FILES['photofile']['error'];
}
// 前端
const formData = new FormData();
formData.append('photofile', fileInput.files[0]);
fetch('./upload.php', { method: 'POST', body: formData })
.then(r => r.text())
.then(html => resultDiv.innerHTML = html);
// 後端 $_FILES 用法完全相容,無需改動
enctype="multipart/form-data" 只對 <form> 原生提交生效,AJAX 需手動設定 Header 或用 FormData 自動處理。