lithemod / upload
一个通用的PHP模块,用于高效管理文件上传,确保无缝集成和强大的错误处理。
v1.0.0
2024-10-02 16:15 UTC
Requires
- lithemod/log: ^1.0
Requires (Dev)
- phpunit/phpunit: ^11.3
This package is auto-updated.
Last update: 2024-10-02 16:16:44 UTC
README
一个简单的PHP模块,用于轻松处理文件上传。
安装
您可以使用Composer轻松安装Upload模块。运行以下命令
composer require lithemod/upload
用法
以下是安装后如何使用Upload
模块的基本示例
-
处理文件上传:创建一个用于文件上传的HTML表单
<form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="fileToUpload" /> <input type="submit" value="Upload" /> </form>
-
处理上传:在您的
upload.php
中,使用Upload
类来处理文件<?php require 'vendor/autoload.php'; // Include Composer's autoloader use Lithe\Base\Upload; if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Create an instance of the Upload class with the uploaded file $upload = new Upload($_FILES['fileToUpload']); // Specify the upload directory and allowed extensions $uploadDir = 'uploads'; $allowedExtensions = ['jpg', 'png', 'gif', 'txt']; // Move the uploaded file $filePath = $upload->move($uploadDir, $allowedExtensions); if ($filePath) { echo "File uploaded successfully: $filePath"; } else { echo "File upload failed."; } }
方法
__construct(array $file)
- 使用文件数据初始化上传实例。
move(string $uploadDir, ?array $allowedExtensions = null): ?string
- 将上传的文件移动到指定的目录。
- 生成一个唯一的文件名以避免覆盖。
- 可选地验证文件扩展名是否允许。
isUploaded(): bool
- 检查文件是否已成功上传。
getMimeType(): ?string
- 检索上传文件的MIME类型。
getSize(): ?int
- 以字节为单位检索上传文件的大小。
错误处理
该模块在各种错误场景中抛出异常,包括
- 无效的文件上传数组
- 上传目录不存在或不可写
- 文件扩展名不允许
请确保在try-catch块中封装模块的使用以适当处理异常。
try { // Upload handling code } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); }
许可
此模块受MIT许可证的许可。有关更多信息,请参阅LICENSE文件。