betamfd / file-handler-bundle
处理来自symfony的文件
v2.11.0
2023-05-23 20:45 UTC
Requires
- php: ^7.2 || ^8.1
- doctrine/orm: ^2.4.8 || ^3.0
- symfony/filesystem: ^3.4 || ^4.0 || ^5.0
- symfony/http-foundation: ^3.4 || ^4.0 || ^5.0
- symfony/monolog-bundle: ^2.11 || ^3.1
- symfony/security: ^3.4 || ^4.4 || ^5.0
- symfony/yaml: ^3.0 || ^4.0 || ^5.0
README
这是一个简单的文件处理器,我为了在多个Symfony项目中使用而构建的。它接收一个处理过的表单,创建一个文件实体,填充它,并将您的文件保存到可自定义的驱动器位置。
这主要是为私有上传编写的 - 需要在登录后才能访问的图像和文档。从版本2.0.0开始,现在可以设置公开路径,以便可以将上传设置到公开位置,例如 /web/
或 /public/
,具体取决于您的配置。此更改需要数据库更新和配置变量的更改。文件上传将默认设置为私有位置。
Composer 安装
composer require betamfd/file-handler-bundle
启用 Bundle
通过将 Bundle 添加到项目中 app/AppKernel.php
文件中注册的 Bundle 列表来启用 Bundle
new BetaMFD\FileHandlerBundle\BetaMFDFileHandlerBundle(),
如果您正在使用较新的 Symfony 版本,请在该项目的 config/bundles.php
文件中启用它
BetaMFD\FileHandlerBundle\BetaMFDFileHandlerBundle::class => ['all' => true],
添加实体
创建一个文件实体,并从模型扩展它。创建一个 ID 字段。它不必是生成值,但如果不是,您可能需要编写自己的 setter 以包含任何自定义逻辑。模型中有一个基本的 setter。
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="file")
* @ORM\Entity(repositoryClass="FileRepository")
*/
class File extends \BetaMFD\FileHandlerBundle\Model\File
{
/**
* @var integer
*
* @ORM\Id
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
}
//any other fields or logic you want
}
<?php
namespace App\Entity;
class FileRepository extends \BetaMFD\FileHandlerBundle\Model\FileRepository
{
// any custom logic you want
}
您可以使用任何您想要的用户实体。目前,唯一的要求是存在一个 getName() 函数,它返回一个字符串,最好是用于记录的用户名。
实现用户界面以确保与所需函数的兼容性。
<?php
// src/App/Entity/User.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="user")
*/
class User
implements \BetaMFD\FileHandlerBundle\Model\UserInterface
{
// ...
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
// ...
}
您必须告诉代码用户实体的位置
# app/config/config.yml
doctrine:
orm:
resolve_target_entities:
# Set this to your User Entity
BetaMFD\FileHandlerBundle\Model\UserInterface: App\Entity\User
自定义设置
有一些设置您应该审查并更新。根据您的 symfony 版本,这可能在 config.yml
或 config/packages/beta_mfd_file_handler.yaml
中
beta_mfd_file_handler:
private_upload_location: '%kernel.project_dir%/var/uploads/'
public_upload_location: '%kernel.project_dir%/web/uploads/'
file_entity: 'App\Entity\File'
使用文件处理器服务
在您的控制器中,注入 \BetaMFD\FileHandlerBundle\Service\FileHandler
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as Controller;
class SomeController extends Controller
{
private $fileService;
public function __construct(
\BetaMFD\FileHandlerBundle\Service\FileHandler $fileService
) {
$this->fileService = $fileService;
}
public function useFormAction(Request $request)
{
//Make sure to use your own upload file form!
$form = $this->createForm(UploadFileType::class);
$form->handleRequest($request);
if ($form->isSubmitted() and $form->isValid()) {
$service = $this->fileService;
$service->allowAll(); //allow all allowed filetypes
//set the file, check the filename and extension
$service->handleForm($form);
//OPTIONAL: rename file
$new_name = 'YourPrefix_' . $service->getUnspacedFileName();
//use isExtensionOkay() or testFileType()
//The file type was tested in handleForm() and isExtensionOkay()
// is just returning the boolean flag set in handleForm()
if ($service->isExtensionOkay() and $service->testName($new_name)) {
//file a-okay!
$file = $service->newFile('rga', $new_name);
if ($file) {
// your custom logic
// like attach file entity to another entity or whatever here
$em = $this->getDoctrine()->getManager();
$em->flush();
//return whatever you need here
$this->addFlash('success', 'File added!');
return $this->redirectToRoute('some_route');
} else {
foreach ($service->getErrors() as $e) {
$this->addFlash('error', $e);
}
return $this->redirectToRoute('some_route');
}
} else {
//there were errors
//add flash errors and stop trying to upload.
foreach ($service->getErrors() as $e) {
$this->addFlash('error', $e);
}
//return something here or don't and just load the page
}
}
$return['files_form'] = $form->createView();
return $this->render('your_awesome_form_template.html.twig', $return);
}
public function straightFileHandlingAction(Request $request)
{
$file = $request->files->get('file');
$service = $this->fileService;
$service->allowAll(); //allow all allowed filetypes
$service->setUploadedFile($file);
//OPTIONAL: rename file
$new_name = 'YourPrefix_' . $service->getUnspacedFileName();
if ($service->testFileType() and $service->testName($new_name)) {
//file a-okay!
$file = $service->newFile('your_subfolder', $new_name);
if ($file) {
// your custom logic
// like attach file entity to another entity or whatever here
$em = $this->getDoctrine()->getManager();
$em->flush();
//return whatever you need here
return new Response();
} else {
$err = $service->getErrors();
//exception or flash bag
throw new \Exception(reset($err));
}
} else {
//there were errors
//exception or flash bag
$err = $service->getErrors();
throw new \Exception(reset($err));
}
//return whatever you need to here
}
}