rogerthomas84/ohupload

一个易于使用的文件上传类

dev-master 2014-12-19 15:32 UTC

This package is auto-updated.

Last update: 2024-09-16 01:09:47 UTC


README

Build Status

在 Packagist 上查看

OhUpload PHP 库

让 PHP 文件上传变得简单!

基本用法

您可以通过查看 example 文件夹来运行此文件的示例。

<?php
$instance = new Upload('form_file_name');
$instance->setTargetDirectory('/path/to/upload/directory');
try {
    if ($instance->receive() === true) {
        // OK.
        $finalPath = $instance->getFinalPath();
    } else {
        // Not OK!
    }
} catch (\Exception $e) {
    // Something happened, possibly a validator. Take a look in:
    // \OhUpload\Validate\Exception for possible Exceptions.
}

添加自定义验证器

您可以轻松地向验证堆栈中添加验证器。下面是一个自定义验证器的示例。所有自定义验证器都必须扩展 \OhUpload\Validate\ValidateBase 并重写 isValid() 方法。从 isValid() 方法返回的预期值必须是

  • \Exception - 不抛出异常,只返回。
  • bool(true)
<?php
namespace My\Custom\Validators;

use OhUpload\Validate\ValidateBase
use My\Custom\Validators\Exception\ExampleException;

class MyBasicCheck extends ValidateBase
{
    /**
     * Run a custom validator.
     * @return
     *   \My\Custom\Validators\Exception\ExampleException
     *   boolean true
     */
    public function isValid()
    {
        if (!empty($this->file)) { // The file from the $_FILES array
            return true;
        }

        return new ExampleException('Validation failed');
    }
}

要将它添加到处理过程中,只需使用

<?php
$instance = new Upload('form_file_name');
$instance->setTargetDirectory('/path/to/upload/directory');
$instance->addValidator('/My/Custom/Validators/MyBasicCheck'); // This is a string, not an instance.
try {
    if ($instance->receive() === true) {
        // OK.
        $finalPath = $instance->getFinalPath();
    } else {
        // Not OK!
    }
} catch (\My\Custom\Validators\MyBasicCheck $e) {
    // Wow! You're custom validator failed!
}