reich/upload

一个优秀的类,可以将文件或多个文件上传到服务器,可以与laravel集成

v2.0 2017-09-10 17:26 UTC

This package is not auto-updated.

Last update: 2024-09-29 02:08:05 UTC


README

Upload.php


用于上传文件或多个文件到服务器的PHP类

安装

使用composer只需运行

composer require reich/upload

或者

您也可以下载src/Upload.php并直接使用。

作为Laravel的包

此类完全集成到Laravel框架,使用Laravel自动发现。如果您不使用v5.5+,您可能需要手动在/config/app.php文件中导入必要的文件路径

  ...
    "providers" => [
      /*
       * Package Service Providers...
       */
      Reich\Upload\Laravel\UploadServiceProvider::class,
    ],

    "aliases" => [
      "Upload" => Reich\Upload\Laravel\UploadFacade::class,
    ]
  ...

使用方法

1) 将位于src目录中的类复制到您的项目中,或者通过composer安装并使用它。
2) 生成一个包含32个字符的加密密钥,或者使用Reich\Upload::generateMeAKey();辅助函数。
3) 请打开我创建的示例/demo/index.php文件,以了解如何使用并更好地理解

确保表单已提交

if(Upload::submitted())
{
  // rest of the code goes here
}

创建类的实例

$upload = new Upload(YOUR-HTML-INPUT-NAME); 

设置您想要上传文件的目录,默认情况下将上传到您的主目录

$upload->setDirectory('img/'); 

您还可以指定如果该目录不存在,则创建此目录

$upload->setDirectory('img/')->create(true); 

您可以使用以下语法设置您想要的上传规则

$upload->addRules([
        'size' => 2000,
        'extensions' => 'png|jpg|pdf'
]);

或者

$upload->addRules([
        'size' => 2000,
        'extensions' => ['png', 'jpg', 'pdf']
]);

仅当您想加密文件名时才设置此选项(为了安全起见,这是可选的)

$upload->encryptFileNames(true);

您还可以指定您想加密特定文件类型,如下所示

$upload->encryptFileNames(true)->only(['jpg']); // only jpg files will be encrypted

或者也可以使用以下语法

$upload->encryptFileNames(true)->only('jpg|png|txt'); // only jpg, png and txt files will be encrypted

设置完成后,只需运行以下命令

$upload->start();

事件

每次成功上传文件时。

$upload->success(function($file) {
  // handle the file
});

如果出现问题,请监听错误。

$upload->error(function($file) {
  // handle the file
});

错误处理

检查是否有错误,如果没有错误,则处理上传

if($upload->unsuccessfulFilesHas())
{
  // display all errors with bootstraps
  $upload->displayErrors();

  // now of course you may formating it differently like so
  foreach($upload->errorFiles as $file)
  {
    // do whatever you want with the file object
    // - $file->name
    // - $file->encryptedName *only if you asked to encrypt*
    // - $file->type
    // - $file->extension
    // - $file->size
    // - $file->error
    // - $file->errorMessage
  }
}
else if($upload->successfulFilesHas())
{
  $upload->displaySuccess();

  // now of course you may formating it differently like so
  foreach($upload->successFiles as $file)
  {
    // do whatever you want with the file object
    // - $file->name
    // - $file->encryptedName *only if you asked to encrypt*
    // - $file->type
    // - $file->extension
    // - $file->size
  }
}

这里还有一个方法,如果您出现问题,可以显示有用的错误

print_r($upload->debug()); // There are some errors only you should look at while setting this up