aminyazdanpanah / handling-file-uploads
轻松将所有上传的文件保存到您的路径目录并提取其信息
Requires
- php: ^7.1
- aminyazdanpanah/php-ffmpeg-video-streaming: 1.1.*
Requires (Dev)
- phpunit/phpunit: 8.0.3
Suggests
- aminyazdanpanah/php-ffmpeg-video-streaming: aminyazdanpanah/php-ffmpeg-video-streaming is suggested for validate video files and create DASH and HLS files.
- gumlet/php-image-resize: gumlet/php-image-resize is suggested for validate image files and resize images
- wapmorgan/unified-archive: wapmorgan/unified-archive is suggested for validate archive files and extracting archives
This package is auto-updated.
Last update: 2022-08-02 16:12:35 UTC
README
通过强大的验证处理图像、视频、音频和存档文件的多重上传。此包允许您在上传文件后处理文件。您可以在文件上传后调整大小、转换、提取等。最后,您可以提取文件的详细信息到数组中。
特性
- 使用配置变量上传多个文件。
- 使用不同规则验证视频、音频、图像和存档文件。
- 管理上传后的文件,如转换、调整大小、提取等。
- 将文件详细信息导出到数组中,您可以将它们轻松插入数据库。
- 兼容 PHP >= 7.1.0。
安装
此版本包仅与 PHP 7.1.0 及更高版本兼容。
通过 composer 安装包
composer require aminyazdanpanah/handling-file-uploads
基本用法
require_once 'vendor/autoload.php'; $export = function($filename){ //Add additional validators and handle file after your file was uploaded. //... }
上传多个文件
$config_files = [ [ 'name' => 'upload_key_name', //The key name that you send your file to the server 'save_to' => $output_path, //The path you'd like to save your file(auto make new directory) 'validator' => [ 'min_size' => 100, //Minimum size is 100KB 'max_size' => 1024 * 2, //Maximum size is 2MB 'allowed_extensions' => ['jpg', 'jpeg', 'png', ...] //Just images are allowed ], 'export' => $export //Get a callback method(whatever you want to do with your file after it was uploaded!) ], [ //... ], ]; $uploads = uploads($config_files)->all(); var_dump("<pre>", $uploads, "</pre>");
上传单个文件
$validator = new Validator(); $validator = $validator->setMinSize(100) ->setMaxSize(1024 * 2) ->setType(['jpg', 'png', 'jpeg']); $upload = new File(); $upload = $upload->file('upload_key_name') ->setValidator($validator) ->setOverride(false) ->setSaveAs('my_dfile') ->save($output_path, $export); var_dump("<pre>", $upload, "</pre>");
重要:请参阅 示例 了解更多信息。在这些页面中,您可以查看使用此包的完整示例。
文档
建议浏览源代码,因为它具有自我文档说明。
配置
在服务器端,您应该创建一个配置数组并将其传递给 uploads()
方法
$config_files = [ [ 'name' => 'upload_image', 'save_to' => __DIR__ . "/images/user/" . time(), 'validator' => [ 'min_size' => 100, 'max_size' => 2048, 'types' => ['jpg', 'jpeg', 'png'] ] ], [ //... ], ]; $uploads = Upload::files($config_files);
有关这些属性的更多信息,请参阅以下表格
配置数组属性
attr | default | mean |
---|---|---|
name | 必填: 必须指定 | 您发送到服务器-PHP($_Files) 的键名。 |
save_to | 必填: 必须指定 | 您希望将文件保存在服务器或计算机上的路径。 |
save_as | 基础文件名 | 您希望保存的名称。 |
override | false | 用同名文件覆盖原始文件。 |
validator | no rules | 在保存之前验证您的文件(请参阅验证表)。 |
export | 不执行任何操作 | 您指定的回调方法,您可以在此方法中指定额外规则并在文件上传后管理文件。 |
验证
保存前
您可以在将上传的文件移动到目的地之前验证上传的文件。您可以在文件上应用一些规则
验证器属性
attr | default | mean |
---|---|---|
min_size | 1 | 允许的文件最小大小(千字节)。 |
max_size | 999999 | 允许的文件最大大小(千字节)。 |
types | '*'(所有内容) | 允许的文件类型(必须是一个数组) |
保存后
您可以通过使用回调方法在将上传的文件移动到目标位置后设置一些规则。为了在保存后验证文件,只需在回调方法中检查您的文件并抛出 AYazdanpanah\SaveUploadedFiles\Exception\Exception
。最后,将其放入配置数组的数组中,并通过 Upload::files($config)
传递它。在回调方法中,您可以管理您的文件。例如,调整图片或视频大小,转换视频,提取归档文件等。之后,您就可以返回您的数据了。
$export = function ($filename) { //Add a Validator: if $filename is not ... if (//condition 1) { throw new Exception("Exception 1"); } //Add a Validator: if $filename is not ... if (//condition 2) { throw new Exception("Exception 2"); } //... //Handles file: resize image or video, convert video, extracting the archive and etc. //... //return whatever you want return $data; } $config = [ [ //... , 'export' => $export ], ]; Upload::files($config);
验证和管理视频文件
有一些因素可以用来验证视频。我推荐使用 PHP-FFMpeg-video-streaming 包,这是一个围绕 PHP-FFmpeg 的包装器。您可以使用它的编解码器、时长、宽度、高度、比例和其他属性来验证您的视频。之后,根据文件是否有效,您可以抛出 Exception
。最后,如您所看到的那样,您可以转换视频或对文件执行其他操作,并导出您的数据
$video_path = __DIR__ . "/videos/$user_id"; $video_name = str_random(); $export_video = function ($filename) use ($video_path, $video_name) { $video = AYazdanpanah\FFMpegStreaming\FFMpeg::create() ->open($filename); //Extracting video meta data $video_metadata = $video->getFirstStream(); //Add a Validator: check if the file is video and video duration is not longer than 1 minute if (!$video_metadata->isVideo() && null === ($duration = $video_metadata->get('duration')) && $duration >= 60) { throw new Exception("Your file is not a video or your video duration is longer than 1 minute!"); } //Add a Validator: check if the video is HD or higher resolution if ($video_metadata->get('width',1) * $video_metadata->get('height', 1) < 1280 * 720) { throw new Exception("Sorry, your video must be at least HD or higher resolution"); } //Add a Validator: check if the video ratio is 16 / 9 if ($video_metadata->getDimensions()->getRatio()->getValue() == 16 / 9) { throw new Exception("Sorry, the video ratio must be 16 / 9"); } //Extracting image and resize it $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(intval($duration / 4)))->save("$video_path/screenshots.jpg"); $image = new ImageResize("$video_path/screenshots.jpg"); $image->resizeToWidth(240)->save("$video_path/{$video_name}_screenshots_small.jpg"); //Extracting gif $video->gif(FFMpeg\Coordinate\TimeCode::fromSeconds(3), new FFMpeg\Coordinate\Dimension(240, 95), 3) ->save("$video_path/{$video_name}_animation.gif"); //Create the dash files(it is better to create a job and dispatch it-do it in the background) mkdir("$video_path/dash/$video_name", 0777, true); dash($filename, "$video_path/dash/$video_name/output.mpd", function ($audio, $format, $percentage) { echo "$percentage % is transcoded\n"; }); //Delete the original file @unlink($filename); return $video_metadata->all(); };
有关更多信息,请阅读 PHP FFMPEG Video Streaming 文档 和 php-ffmpeg 文档。
验证和管理图像文件
为了验证和管理图像,我推荐使用 php-image-resize 包。有关更多信息,我强烈建议您阅读 php-image-resize 文档。之后,根据文件是否有效,您可以抛出 Exception
。最后,您可以导出您的数据
$image_path = __DIR__ . "/images/user/$user_id"; $export_image = function ($filename) use ($image_path) { //Add a Validator: check if the file is image if (!is_type("image", $filename)) { throw new Exception("Your file is not an image!"); } $image_metadata = exif_read_data($filename); //Add a Validator: check whether the image is square or not if ($image_metadata['COMPUTED']['Width'] / $image_metadata['COMPUTED']['Height'] != 1) { throw new Exception("Your image must be square!"); } if (!is_dir($image_path . "/thumbnail")) { mkdir($image_path . "/thumbnail", 0777, true); } // Resize and crop your image $image = new ImageResize($filename); $image->resizeToWidth(50)->save($image_path . "/thumbnail/thumb_50.jpg"); $image->resizeToWidth(100)->save($image_path . "/thumbnail/thumb_100.jpg"); $image->resizeToWidth(240)->save($image_path . "/thumbnail/thumb_240.jpg"); $image->resizeToBestFit(500, 300)->save($image_path . "/thumbnail/thumb_500_300.jpg"); $image->crop(200, 200)->save($image_path . "/thumbnail/thumb_crop_200_200.jpg"); return $image_metadata; };
验证和管理归档文件
为了验证和管理归档文件,我推荐使用 UnifiedArchive 包。有关更多信息,我强烈建议您阅读 UnifiedArchive 文档。之后,根据文件是否有效,您可以抛出 Exception
。最后,您可以导出您的数据
$archive_path = __DIR__ . "/archive/$user_id"; $archive_name = str_random(); $archive_export = function ($filename) use ($archive_path, $archive_name) { mkdir("$archive_path/$archive_name"); $archive = UnifiedArchive::open($filename); //Add a Validator: check whether the file is able to open or not if (null === $archive) { unlink($filename); throw new Exception("Sorry!we could not open the archive. Please check whether your extension has been installed or not. Your file may be corrupted or is encrypted"); } //Add a Validator: check whether the profile.jpg is in archive or not if (!$archive->isFileExists('profile.jpg')) { unlink($filename); throw new Exception("Sorry!we could not find 'profile.jpg' in the archive"); } //Extracting files $archive->extractFiles("$archive_path/$archive_name"); return $archive->getFileNames(); };
验证和管理音频文件
为了验证和管理音频文件,我推荐使用 php-ffmpeg 包。有关更多信息,我强烈建议您阅读 php-ffmpeg。之后,根据文件是否有效,您可以抛出 Exception
。最后,您可以导出您的数据
$audio_path = __DIR__ . "/audios/$user_id"; $audio_name = str_random(); $audio_export = function ($filename) use ($audio_path, $audio_name) { mkdir($audio_path . '/flac'); $audio = AYazdanpanah\FFMpegStreaming\FFMpeg::create() ->open($filename); $audio_metadata = $audio->getFirstStream(); //Add a Validator: check if the file is audio if (!$audio_metadata->isAudio() && null === ($duration = $audio_metadata->get('duration')) && $duration <= 60) { throw new Exception("Sorry, your file is not an audio or your audio duration must be longer than 1 minute!"); } //Add a Validator: check if the file is mp3 if (!strstr($audio_metadata->get('codec_name'), 'mp3')) { throw new Exception("Sorry, your audio format must be mp3!"); } //Convert the file into flac format $format = new FFMpeg\Format\Audio\Flac(); $format->on('progress', function ($audio, $format, $percentage) { echo "$percentage % transcoded\n"; }); $format ->setAudioChannels(2) ->setAudioKiloBitrate(256); $audio->save($format, "$audio_path/flac/$audio_name.flac"); return $audio_metadata->all(); };
导出数据
上传后,类返回一个实例为 Filter
的对象。您可以通过使用 all()
方法导出上传的所有详细信息。
print_r($uploads->all());// Returns all uploads and their details.
其他可能的方法
print_r($uploads->get(['upload_video', 'upload_raw']));// Returns specified uploads and their details. print_r($uploads->except(['upload_raw', 'upload_image']));// Returns all uploads and their details except those ones specified. print_r($uploads->first());// Returns first upload and it's detail. print_r($uploads->succeeded());// Returns all succeeded uploads and their details. print_r($uploads->failed());// Returns all failed uploads and their details. print_r($uploads->names());// Returns all upload names. print_r($uploads->count());// Returns the number of uploads
示例
要查看完整的示例,请访问 示例。
贡献
我非常欢迎您的帮助来改进、纠正和添加规范。请提交一个issue或提交一个pull request。
有关更多信息,请参阅贡献文件。
安全
如果您在此包中发现了安全漏洞,请通过以下方式发送电子邮件给Amin Yazdanpanah:contact [AT] aminyazdanpanah • com。
致谢
许可证
MIT许可证(MIT)。有关更多信息,请参阅许可证文件。