如何将PHP图片上传适配为视频上传?求MVC硬编码非JS教程
Since you already have a working image upload setup, adapting it for video follows the same MVC pattern—we just need to tweak validation, file handling, and constraints to support .avi and .mp4 (and other video formats you want). Let's break this down step by step, no fancy JS required.
1. View: The Upload Form
Your form will look almost identical to your image upload form, but we'll add explicit hints for video files and enforce the correct encoding. Always use enctype="multipart/form-data"—this is non-negotiable for file uploads.
<!-- views/video_upload_form.php --> <form method="POST" action="/video/upload" enctype="multipart/form-data"> <label for="video_file">Select Video File:</label> <input type="file" id="video_file" name="video_file" accept=".avi,.mp4"> <button type="submit">Upload Video</button> <?php if (isset($error)): ?> <p style="color: red;">* <?= $error ?></p> <?php endif; ?> <?php if (isset($success)): ?> <p style="color: green;">✅ <?= $success ?></p> <?php endif; ?> </form>
The accept attribute helps guide users to pick video files, but never trust it alone—we'll validate everything server-side.
2. Model: Video Upload Handler
You can either extend your existing image upload class or create a dedicated VideoUpload model. The key differences are validating video-specific MIME types/extensions and handling larger file sizes. Here's a hard-coded MVC model example:
// models/VideoUpload.php class VideoUpload { private $allowedExtensions = ['avi', 'mp4', 'mov']; // Add more formats if needed private $allowedMimeTypes = [ 'video/avi', 'video/mp4', 'video/quicktime' ]; private $uploadDir = 'uploads/videos/'; // Ensure this folder exists and is writable! private $maxFileSize = 50 * 1024 * 1024; // 50MB - adjust based on your needs public function upload($file) { // Step 1: Check for upload errors if ($file['error'] !== UPLOAD_ERR_OK) { return $this->getUploadError($file['error']); } // Step 2: Validate file size if ($file['size'] > $this->maxFileSize) { return "File too large. Max allowed size is " . $this->formatSize($this->maxFileSize); } // Step 3: Validate file extension and MIME type $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); $fileMimeType = mime_content_type($file['tmp_name']); if (!in_array($fileExtension, $this->allowedExtensions) || !in_array($fileMimeType, $this->allowedMimeTypes)) { return "Invalid file type. Allowed formats: " . implode(', ', $this->allowedExtensions); } // Step 4: Generate unique filename to avoid overwrites $uniqueFilename = uniqid('video_', true) . '.' . $fileExtension; $destination = $this->uploadDir . $uniqueFilename; // Step 5: Move uploaded file to target directory if (!move_uploaded_file($file['tmp_name'], $destination)) { return "Failed to save file. Check directory permissions."; } // Return success with filename (you'll likely want to store this in a database) return ['success' => true, 'filename' => $uniqueFilename]; } private function getUploadError($errorCode) { switch ($errorCode) { case UPLOAD_ERR_INI_SIZE: return "File exceeds server's max upload size."; case UPLOAD_ERR_FORM_SIZE: return "File exceeds form's max upload size."; case UPLOAD_ERR_PARTIAL: return "File was only partially uploaded."; case UPLOAD_ERR_NO_FILE: return "No file was selected."; default: return "Unknown upload error."; } } private function formatSize($bytes) { $units = ['B', 'KB', 'MB', 'GB']; for ($i = 0; $bytes > 1024 && $i < count($units)-1; $i++) { $bytes /= 1024; } return round($bytes, 2) . ' ' . $units[$i]; } }
3. Controller: Handle Form Submission
Your controller ties the view and model together—receives the POST request, calls the upload logic, and passes feedback to the view:
// controllers/VideoController.php class VideoController { public function upload() { $data = []; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $videoUpload = new VideoUpload(); $result = $videoUpload->upload($_FILES['video_file']); if (is_array($result) && $result['success']) { // Optional: Save $result['filename'] to your database here $data['success'] = "Video uploaded successfully! Filename: " . $result['filename']; } else { $data['error'] = $result; } } // Render the view with feedback data include 'views/video_upload_form.php'; } }
4. Critical Server Configuration Tweaks
Videos are large, so adjust your php.ini settings to avoid upload failures:
upload_max_filesize: Set to at least your max video size (e.g.,50M)post_max_size: Should be larger thanupload_max_filesize(e.g.,60M)max_execution_time: Increase for longer uploads (e.g.,300for 5 minutes)max_input_time: Matchmax_execution_time(e.g.,300)
Restart your web server after making these changes.
Key Reminders
- Never rely on client-side validation: Users can bypass the
acceptattribute—always validate MIME types and extensions server-side. - File storage: For production, consider cloud storage (like S3) instead of local storage, but the MVC logic stays the same.
- Cleanup: Add a cron job to delete old/unused videos to save server space.
内容的提问来源于stack exchange,提问作者HeroOfTales

