如何实现添加文章(Add post)页面的文件可选上传功能?
Hey Sarah, I've looked at your code snippet, and here's how you can adjust things to let users choose whether to upload files (images or other post files) instead of making them required:
Step 1: Adjust File Validation Logic
The key issue with your current code is that it checks file sizes regardless of whether the user uploaded a file. We need to only run those size checks when a file is actually uploaded.
For the Post Image
Update your image handling code to first check if a file was uploaded before validating its size:
// Handle post image (optional upload) if ($_FILES['image']['error'] !== UPLOAD_ERR_NO_FILE) { $file_size = $_FILES['image']['size']; // Only check size if a file was uploaded if ($file_size > 2097152) { $missing_input[] = 'The Post image must be less than 2MB'; } // Add logic here to save/process the uploaded image if needed } else { // No image uploaded? Use your default image $target = "../posts/default.png"; $check_upload = true; }
For the Post File
Do the same for the other post file (adjust the name attribute if your input uses a different value than post_file):
// Handle post file (optional upload) if ($_FILES['post_file']['error'] !== UPLOAD_ERR_NO_FILE) { $file_size1 = $_FILES['post_file']['size']; // Only check size if a file was uploaded if ($file_size1 > 2097152) { $missing_input[] = 'The Post file must be less than 2MB'; } // Add logic here to save/process the uploaded file if needed } else { // No file uploaded? No error needed—just skip processing // You can set a default value or leave it null depending on your database setup }
Step 2: Update Your Frontend Form
Make sure your file input fields don't have the required attribute (if you added it earlier). This prevents the browser from forcing users to upload a file before submitting:
<!-- Optional image upload --> <input type="file" name="image" accept="image/*"> <!-- Optional post file upload --> <input type="file" name="post_file">
Step 3: Verify Error Handling
Now, the $missing_input array will only contain errors if a user uploaded a file that's too large. If they choose not to upload anything, no errors are added, and the form can submit successfully.
Why This Works
By checking $_FILES['input_name']['error'] !== UPLOAD_ERR_NO_FILE, we're confirming that a file was actually sent with the form. Only then do we run size validation. For cases where no file is uploaded, we either use a default (like your default.png) or just skip processing entirely—no errors thrown.
内容的提问来源于stack exchange,提问作者Sarah AH

