You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP文件上传表单:alert提示后如何阻止上传并重定向?

解决PHP上传表单JS文件大小校验后仍提交的问题

核心问题原因

你之前的代码没阻止表单的默认提交行为——哪怕弹出了提示,表单还是会继续执行提交流程,导致跳转操作被覆盖,所以window.location没生效。

具体修改方案

1. 给表单绑定提交验证事件

在HTML表单标签中添加onsubmit属性,指定验证函数,让表单提交前先执行校验:

<form action="upload.php" method="POST" enctype="multipart/form-data" onsubmit="return validateFileSize()">
    <input type="file" name="uploaded_file" id="uploaded_file">
    <input type="submit" value="Upload File">
</form>

2. 编写验证函数,阻止提交+跳转

在<script>标签中编写校验逻辑,关键是检测到文件过大时返回false,彻底终止表单提交,再执行跳转:

function validateFileSize() {
    const fileInput = document.getElementById('uploaded_file');
    const maxSize = 1048576; // 1MB = 1024*1024字节

    // 检查是否选中了文件
    if (fileInput.files.length > 0) {
        const file = fileInput.files[0];
        if (file.size > maxSize) {
            alert("File too large. Try again by uploading smaller size.");
            // 跳转回空白上传页
            window.location.href = 'upload.php';
            // 阻止表单提交
            return false;
        }
    }
    // 文件大小符合要求,允许表单提交
    return true;
}

3. 服务器端校验(不可省略)

前端校验可以被绕过,必须在服务器端再做一次大小检查,PHP代码示例:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $maxSize = 1048576; // 1MB
    $uploadDir = './uploads/';

    // 确保目录存在
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    // 检查文件上传状态
    if (isset($_FILES['uploaded_file']) && $_FILES['uploaded_file']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['uploaded_file'];
        if ($file['size'] > $maxSize) {
            echo "<script>alert('File too large. Try again by uploading smaller size.'); window.location.href='upload.php';</script>";
            exit;
        }
        // 执行文件上传操作
        $targetPath = $uploadDir . basename($file['name']);
        if (move_uploaded_file($file['tmp_name'], $targetPath)) {
            echo "File uploaded successfully!";
        } else {
            echo "Failed to upload file.";
        }
    }
}
?>

补充说明

  • return false是阻止表单提交最直接的方式,适配绝大多数浏览器;
  • 若想用event.preventDefault()替代,需把事件对象传入函数:onsubmit="validateFileSize(event)",然后在函数内添加event.preventDefault();
  • 跳转代码的顺序不影响结果,只要确保先阻止表单提交,就能让跳转生效。

内容的提问来源于stack exchange,提问作者Aquaholic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 00:25:16