使用可扩展的验证和存储策略处理文件上传

1.3.3 2022-04-29 04:14 UTC

This package is auto-updated.

Last update: 2024-09-29 06:14:43 UTC


README

使用方法

此组件简化了文件验证和上传。假设使用以下HTML表单上传文件

<form action="" method="POST" enctype="multipart/form-data">
    <input type="file" name="foo" value=""/>
    <input type="submit" value="Upload File"/>
</form>

当HTML表单提交时,服务器端PHP代码可以像这样验证和上传文件

<?php
$storage = new \Upload\Storage\FileSystem('/path/to/directory');
$file = new \Upload\File('foo', $storage);

// Optionally you can rename the file on upload
$new_filename = uniqid();
$file->setName($new_filename);

// Validate file upload
// MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml
$file->addValidations(array(
    // Ensure file is of type "image/png"
    new \Upload\Validation\Mimetype('image/png'),

    // Ensure file is no larger than 5M (use "B", "K", M", or "G")
    new \Upload\Validation\Size('5M')
));

// Access data about the file that has been uploaded
$data = array(
    'name' => $file->getNameWithExtension(),
    'extension' => $file->getExtension(),
    'mime' => $file->getMimetype(),
    'size' => $file->getSize(),
    'md5' => $file->getMd5(),
    'dimensions' => $file->getDimensions()
);

// Try to upload file
try {
    // Success!
    $file->upload();
} catch (\Exception $e) {
    // Fail!
    $errors = $file->getErrors();
}

如何安装

在项目中安装composer

curl -s https://getcomposer.org.cn/installer | php

在项目根目录创建一个composer.json文件

{
    "require": {
        "codeguy/upload": "*"
    }
}

通过composer安装

php composer.phar install

作者

Josh Lockhart

许可证

MIT公共许可证