PHP code example of qingbing / pf-tools-upload

1. Go to this page and download the library: Download qingbing/pf-tools-upload library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

qingbing / pf-tools-upload example snippets


            // 获取上传实例
            $upload = UploadFile::getInstanceByName('upload');
            if (null === $upload) {
                throw new Exception('请选择要上传的文件');
            }
            $filename = time() . '.' . $upload->getExtensionName();
            // 上传文件
            if (!$upload->saveAs(UploadManager::getPath('avatars', true) . DS . $filename)) {
                throw new Exception('上传图像错误,请联系管理员');
            }
            $this->success('文件上传成功', -1);

            // 获取上传实例
            $upload = UploadFile::getInstance($model, 'upload');
            if (null === $upload) {
                throw new Exception('请选择要上传的文件');
            }
            $filename = time() . '.' . $upload->getExtensionName();
            // 上传文件
            if (!$upload->saveAs(UploadManager::getPath('model', true) . DS . $filename)) {
                throw new Exception('上传图像错误,请联系管理员');
            }
            $this->success('文件上传成功', -1);

class TestUploadValid extends FormModel
{
    public $version;
    public $upload;

    public function rules()
    {
        return [
            ['version', 'string', 'allowEmpty' => false],
            ['upload', \UploadFile::VALID_CLASS, 'allowEmpty' => false, 'types' => ['gif', 'png', 'jpg', 'jpeg'],],
        ];
    }

    /**
     * 上传文件并处理
     * @return bool
     * @throws \Exception
     */
    public function save()
    {
        if (!$this->validate()) {
            return false;
        }
        // 获取上传实例
        $upload = \UploadFile::getInstance($this, 'upload');
        if (null === $upload) {
            $this->addError('upload', '请选择要上传的文件');
            return false;
        }
        $filename = time() . '.' . $upload->getExtensionName();
        // 上传文件
        if (!$upload->saveAs(UploadManager::getPath('valid', true) . DS . $filename)) {
            $this->addError('upload', '上传图像错误');
        }
        return true;
    }
}

            $model->setAttributes($_POST['TestUploadValid']);
            if ($model->save()) {
                $this->success('', -1);
            } else {
                $this->failure('操作失败', $model->getErrors());
            }

        // 获取上传文件目录,无则创建
        var_dump(UploadManager::getPath('valid', true));

        // 获取上传文件的访问URL
        var_dump(UploadManager::getUrl('avatars') . '1546831660.txt');
        var_dump(UploadManager::getUrl('avatars', true) . '1546831660.txt');