萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP + JavaScript 實現圖片非同步上傳(AJAX + FormData)

架構概覽

前端使用 FormData + fetch()(或 XMLHttpRequest)非同步上傳,後端 PHP 接收 $_FILES 儲存並回傳 JSON 路徑。全程無頁面重整,體驗流暢。

後端 upload.php

<?php
header('Content-Type: application/json; charset=utf-8');

if (!isset($_FILES['myfile'])) {
    echo json_encode(['error' => '無檔案上傳']);
    exit;
}

$uploadDir = 'images/' . date('Ymd') . '/';
$absDir    = __DIR__ . '/' . $uploadDir;

if (!is_dir($absDir)) {
    mkdir($absDir, 0777, true);
}

$file = $_FILES['myfile'];
$ext  = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowExt = ['jpg','jpeg','png','gif','webp'];

if (!in_array($ext, $allowExt, true)) {
    echo json_encode(['error' => '副檔名不允許']);
    exit;
}

$newName = time() . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
$dest    = $absDir . $newName;

if (move_uploaded_file($file['tmp_name'], $dest)) {
    echo json_encode([
        'success' => true,
        'url'     = $uploadDir . $newName,
        'name'    => $file['name']
    ]);
} else {
    echo json_encode(['error' => '移動檔案失敗']);
}
?>

前端 index.html

<input type="file" id="fileInput" accept="image/*">
<button id="uploadBtn">上傳</button>
<div id="preview"></div>

<script>
document.getElementById('uploadBtn').addEventListener('click', async () => {
    const file = document.getElementById('fileInput').files[0];
    if (!file) return alert('請選擇圖片');

    const form = new FormData();
    form.append('myfile', file);

    try {
        const res = await fetch('upload.php', {method: 'POST', body: form});
        const data = await res.json();
        if (data.success) {
            document.getElementById('preview').innerHTML =
                `<img src="${data.url}" alt="${data.name}" style="max-width:300px">`;
        } else {
            alert('上傳失敗:' + data.error);
        }
    } catch (e) {
        console.error(e);
        alert('網路錯誤');
    }
});
</script>

安全加固清單

  • 檢查 MIME 型別:finfo_file(finfo_open(FILEINFO_MIME_TYPE), $tmp)
  • 限制檔案大小:ini_set('upload_max_filesize', '5M') + 前端 file.size 檢查
  • 儲存目錄設為 不可執行(Nginx/Apache 禁用 PHP 解析)
  • 檔案重命名避免覆蓋與路徑遍歷
  • 上傳後掃毒(ClamAV)再對外公開
copyright © 萬盛學電腦網 all rights reserved