求助:GitHub获取的文件上传PHP代码调用失败,求正确用法
解决PHP文件上传返回"Upload Error"的问题
Hey, let's break down why your upload is failing and fix it step by step. The biggest red flag I see right away is in your HTML form setup—let's start there.
1. 修复HTML表单(核心问题)
你的表单使用了method="get",并且缺少文件上传必需的enctype属性。文件上传必须使用POST方法,同时指定enctype="multipart/form-data"——GET无法正确处理文件内容。以下是修正后的表单:
<form action="file.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="action" value="upload"> <input type="hidden" name="path" value="class/"> <input type="file" name="upload"> <input type="submit" class="btn btn-success btn-sm" value="upload to specific dir"> </form>
注意:我移除了文件输入框和提交按钮的readonly属性——这些属性在这里没有意义,文件输入框需要交互才能选择文件。
2. 为$_FILES添加错误检查
你的PHP代码没有检查文件是否真的上传成功(跳过了$_FILES['upload']['error']的判断)。这是一个很大的疏漏——上传失败有很多原因(文件过大、临时文件夹问题等)。更新你的上传函数,加入这个检查:
public function upload(){ // 首先检查文件上传是否存在错误 if ($_FILES['upload']['error'] !== UPLOAD_ERR_OK) { $this->status = "error"; // 将错误代码映射为易读的提示信息 $errorMessages = [ UPLOAD_ERR_INI_SIZE => '文件大小超过php.ini中upload_max_filesize的限制', UPLOAD_ERR_FORM_SIZE => '文件大小超过表单中MAX_FILE_SIZE的限制', UPLOAD_ERR_PARTIAL => '文件仅部分上传', UPLOAD_ERR_NO_FILE => '未选择要上传的文件', UPLOAD_ERR_NO_TMP_DIR => '未找到临时文件夹', UPLOAD_ERR_CANT_WRITE => '无法将文件写入磁盘', UPLOAD_ERR_EXTENSION => '文件上传被扩展程序阻止' ]; $this->message = $errorMessages[$_FILES['upload']['error']] ?? '未知上传错误'; $this->respond(); return; } // 检查路径是否为目录 if(is_file($this->path)){ $this->status = "error"; $this->message = "Path Not A Directory"; }else{ // 确保目标目录存在(不存在则创建) if (!is_dir($this->path)) { mkdir($this->path, 0755, true); // 递归创建目录 } $target = $this->path . "/" . basename($_FILES['upload']['name']); // 可选:避免覆盖已有文件(良好实践) if (file_exists($target)) { $this->status = "error"; $this->message = "File already exists"; } elseif(move_uploaded_file($_FILES['upload']['tmp_name'], $target)) { $this->status = "success"; $this->message = "文件上传成功"; // 添加成功提示信息,增加清晰度 }else{ $this->status = "error"; $this->message = "Upload Error: 无法移动上传的文件"; } } $this->respond(); }
3. 验证服务器权限
class/目录需要给Web服务器用户(Linux通常是www-data,Windows是IUSR)写入权限。如果是Linux服务器,可运行chmod 755 class/或chown www-data:www-data class/。- 确保PHP临时上传目录(可通过
echo sys_get_temp_dir();查看)也有写入权限。
4. 检查PHP配置限制
打开你的php.ini文件,验证以下设置:
upload_max_filesize:必须大于你要上传的文件大小post_max_size:必须大于upload_max_filesizemax_execution_time:给大文件上传留出足够的时间
完成这些修改后,再次测试上传——这应该能解决"Upload Error"的问题。
内容的提问来源于stack exchange,提问作者Achilles Balaba Revalliv
相关产品推荐
相关产品推荐

