未选择文件时网页显示上传错误,求PHP上传功能修复方案
解决未选择文件时网页提前显示错误提示的问题
嘿,我帮你分析下问题根源:你的PHP代码在页面刚加载的时候就直接执行了,不管用户有没有点击上传按钮。当页面首次打开(是GET请求,不是上传的POST请求),$_FILES数组里根本没有reservation_Attachment这个键,所以才会抛出那些"Undefined index"的通知,同时直接显示错误提示。
咱们来一步步修复这个问题,同时优化你重复的上传逻辑:
修复后的完整代码
<td> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <input type="file" name="reservation_Attachment" size="50" /> <br /> <input type="submit" value="Upload" /> </form> <?php // 只有当用户提交了表单(POST请求),才执行上传逻辑 if ($_SERVER['REQUEST_METHOD'] === 'POST') { // 检查文件是否存在且上传无错误 if (isset($_FILES['reservation_Attachment']) && $_FILES['reservation_Attachment']['error'] === UPLOAD_ERR_OK) { $targetfolder = "attachment/"; // 确保目标文件夹存在,不存在就创建 if (!file_exists($targetfolder)) { mkdir($targetfolder, 0755, true); } $targetfile = $targetfolder . basename($_FILES['reservation_Attachment']['name']); $file_type = $_FILES['reservation_Attachment']['type']; // 允许的文件类型 $allowed_types = ["application/pdf", "image/gif", "image/jpeg", "image/png"]; if (in_array($file_type, $allowed_types)) { if (move_uploaded_file($_FILES['reservation_Attachment']['tmp_name'], $targetfile)) { echo "The file ". basename($_FILES['reservation_Attachment']['name']). " is uploaded successfully!"; } else { echo "Problem uploading file: Could not move file to target directory."; } } else { echo "You may only upload PDFs, JPEGs, GIFs or PNG files.<br>"; } } else { // 处理没有选择文件或者上传错误的情况 if (isset($_FILES['reservation_Attachment']) && $_FILES['reservation_Attachment']['error'] !== UPLOAD_ERR_OK) { switch ($_FILES['reservation_Attachment']['error']) { case UPLOAD_ERR_NO_FILE: echo "Error: No file selected for upload."; break; case UPLOAD_ERR_INI_SIZE: echo "Error: File exceeds maximum upload size set in php.ini."; break; default: echo "Error: File upload failed with error code: ". $_FILES['reservation_Attachment']['error']; } } else { echo "Error: No file data received."; } } } ?> </td> </tr>
关键修复点说明
- 判断POST请求:用
$_SERVER['REQUEST_METHOD'] === 'POST'确保只有用户点击上传按钮后,才执行上传逻辑,页面首次加载时不会触发任何错误提示 - 检查上传状态:用
$_FILES['reservation_Attachment']['error'] === UPLOAD_ERR_OK来准确判断文件是否成功上传,比只检查isset更可靠(能覆盖用户选了文件但上传过程中出错的情况) - 创建目标文件夹:添加
mkdir确保attachment/文件夹存在,避免因为文件夹不存在导致上传失败 - 合并重复逻辑:你原来的代码有两段几乎一样的上传代码,现在合并成一套,减少冗余
- 详细错误提示:根据不同的上传错误码给出具体提示,方便调试和用户理解
- 扩展允许的文件类型:增加了PNG类型(可选,你可以根据需要删除或修改)
这样修改后,页面首次加载时不会显示任何错误,只有当用户提交表单后,才会根据情况显示上传成功、文件类型错误或者未选择文件的提示。
内容的提问来源于stack exchange,提问作者Nur Ammirah Abdul Manap
相关产品推荐
相关产品推荐

