gravitypdf / upload
使用可扩展的验证和存储策略处理文件上传
3.0.1
2022-12-11 23:50 UTC
Requires
- php: ^7.3 || ~8.0.0 || ~8.1.0 || ~8.2.0
- ext-fileinfo: *
Requires (Dev)
Replaces
- codeguy/upload: 1.3.2
README
此组件简化了文件验证和上传。
为什么这个库会被分支出来?
- 原始库已被废弃(自2018年以来未更新)
- 将命名空间从 \Upload 更改为 \GravityPdf\Upload
- 将最低PHP版本提升到7.3+
- 清理文件名和扩展名,并添加UTF-8文件名支持
- 严格类型检查
- 添加了
FileSystem::getDirectory()
和FileInfo::setNameWithExtension()
方法 - 包含来自上游仓库的未发布代码
- PSR-12代码格式化
- 自动化工具:PHPUnit、PHPStan、PHPCS和PHP语法检查器
待办事项:支持PSR-7和PSR-17(寻求帮助)
安装
composer require gravitypdf/upload
用法
假设使用以下HTML表单上传文件
<form method="POST" enctype="multipart/form-data"> <input type="file" name="foo" value=""/> <input type="submit" value="Upload File"/> </form>
当HTML表单提交时,服务器端PHP代码可以像这样验证和上传文件
$storage = new \GravityPdf\Upload\Storage\FileSystem('/path/to/directory'); // To override existing files when uploading, pass `true` as the second parameter // $storage = new \GravityPdf\Upload\Storage\FileSystem('/path/to/directory', true); $file = new \GravityPdf\Upload\File('foo', $storage); // Validate file upload // MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml $file->addValidations([ // Ensure file is of type "image/png" new \GravityPdf\Upload\Validation\Mimetype('image/png'), new \GravityPdf\Upload\Validation\Extension('png'), //You can also add multi mimetype validation or extensions //new \GravityPdf\Upload\Validation\Mimetype(['image/png', 'image/gif']) //new \GravityPdf\Upload\Validation\Extension(['png', 'gif']), // Ensure file is no larger than 5M (use "B", "K", M", or "G") new \GravityPdf\Upload\Validation\Size('5M'), ]); // Access data about the file // If upload accepts multiple files an array will be returned for each of these $data = [ 'name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5(), 'dimensions' => $file->getDimensions(), ]; // If you have an upload field that accepts multiple files you can access each file's info individually $firstFileName = $file[0]->getNameWithExtension(); if(isset($file[1])) { $secondFileName = $file[1]->getNameWithExtension(); } // or loop over all files for this key foreach($file as $i => $upload) { $name = $upload->getNameWithExtension(); $upload->setName('file-'.$i); } // Try to upload file(s) try { // Success! $file->upload(); } catch (\Exception $e) { // Validation errors $errors = $file->getErrors(); if(count($errors) === 0) { // Failed for another reason, like the file already exists $error = $e->getMessage(); } }
作者
许可证
MIT公共许可证