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

开发文件上传页面时遭遇POST请求405 (Method Not Allowed)错误求助

解决POST请求返回net::ERR_ABORTED 405 (Method Not Allowed)错误

问题根源

你当前使用的http://127.0.0.1:5500是VS Code Live Server这类静态文件服务器,它仅能处理HTML、CSS、JS等静态资源,不支持解析PHP脚本。当你向upload.php发送POST请求时,服务器无法识别PHP文件的处理逻辑,直接返回405方法不允许错误。

解决方案

1. 切换到PHP兼容的服务器运行项目

方法一:使用XAMPP/WAMP集成环境

  • 将项目文件夹放到XAMPP的htdocs目录(或WAMP的www目录)
  • 启动Apache服务器,访问地址改为http://localhost/你的项目文件夹名/upload.php
  • 修改JS代码里的endpoint为对应路径,比如'/你的项目文件夹名/upload.php'

方法二:使用PHP内置服务器

  • 打开命令行,进入项目根目录
  • 执行命令:php -S localhost:8000
  • 访问地址改为http://localhost:8000/upload.php,JS里的endpoint直接写'upload.php'即可

2. 修正PHP代码的潜在问题

你的PHP代码存在语法错误和逻辑漏洞,修正后版本:

<?php
// 检查文件是否正常上传
if (isset($_FILES['inpFile']) && $_FILES['inpFile']['error'] === UPLOAD_ERR_OK) {
    $targetDir = 'videos/';
    // 自动创建videos目录(如果不存在)
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0755, true);
    }
    $targetPath = $targetDir . basename($_FILES['inpFile']['name']);
    
    // 移动上传文件并反馈结果
    if (move_uploaded_file($_FILES['inpFile']['tmp_name'], $targetPath)) {
        echo json_encode(['status' => 'success', 'message' => '文件上传完成']);
    } else {
        echo json_encode(['status' => 'error', 'message' => '文件移动失败']);
    }
} else {
    $errorMsg = isset($_FILES['inpFile']) ? '上传错误码:' . $_FILES['inpFile']['error'] : '未检测到上传文件';
    echo json_encode(['status' => 'error', 'message' => $errorMsg]);
}
?>

3. 完善JS的请求处理

给fetch添加成功回调,方便调试:

mainform.addEventListener('submit', e => {
    e.preventDefault();

    const endpoint = 'upload.php'; // 注意根据服务器地址调整路径
    const formData = new FormData();
    formData.append('inpFile', inpFile.files[0]);

    fetch(endpoint, {
        method: "POST",
        body: formData
    })
    .then(response => {
        if (!response.ok) throw new Error(`HTTP错误:${response.status}`);
        return response.json();
    })
    .then(result => {
        console.log(result);
        // 这里可以添加上传成功后的UI提示
    })
    .catch(console.error);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:41:31