<?php namespace MyFolder\MyBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * Table * * @ORM\Table(name="table") * @ORM\Entity */ class Table { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255, nullable=true) */ private $filePath; } . /:
<?php namespace MyFolder\MyBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Show\ShowMapper; class NameAdmin extends Admin { protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('name'); } protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('name') } protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier('name') } }
{% extends 'SonataAdminBundle::standard_layout.html.twig' %} {% block stylesheets %} {{ parent() }} <link href="{{ asset('bundles/mybundle/css/admin/style.css') }}" rel="stylesheet" type="text/css" /> {% endblock %} {% block javascripts %} {{ parent() }} <script src="{{ asset('bundles/mybundle/js/admin/jquery.filedrop.js') }}"></script> <script src="{{ asset('bundles/mybundle/js/admin/js.fileDropBlock.js') }}"></script> <script src="{{ asset('bundles/mybundle/js/admin/js.fileLoadByDefault.js') }}"></script> <script src="{{ asset('bundles/mybundle/js/admin/init.js') }}"></script> {% endblock %}
sonata_admin: title: My Admin Panel templates: ## default global templates layout: MyFolderMyBundle:Admin:sonata_admin_base_layout.html.twig
<script src="{{ asset('bundles/mybundle/js/admin/jquery.filedrop.js') }}"></script> <script src="{{ asset('bundles/mybundle/js/admin/js.fileDropBlock.js') }}"></script> <script src="{{ asset('bundles/mybundle/js/admin/js.fileLoadByDefault.js') }}"></script> <script src="{{ asset('bundles/mybundle/js/admin/init.js') }}"></script>
function fileDropBlock(block, type) { var allowType = { 'img': ['image/jpeg', 'image/png', 'image/gif'] }; block.filedrop({ url: '/upload-file', # url paramname: 'file', # . name input fallbackid: 'upload_button', maxfiles: 1, # - maxfilesize: 2, # mb # . error: function (err, file) { switch (err) { case 'BrowserNotSupported': console.log('Old browser'); break; case 'FileTooLarge': console.log('File Too Large'); break; case 'TooManyFiles': console.log('Only 1 file can be downloader'); break; case 'FileTypeNotAllowed': console.log('Wrong file type'); break; default: console.log('Some error'); } }, allowedfiletypes: allowType[type], # dragOver: function () { block.addClass('active-drag-block'); }, dragLeave: function () { block._removeClass('active-drag-block'); }, uploadFinished: function (i, file, response) { block.find('input[type="text"]').val(response.filePath); # } }) }
var arrayType = { 'img': [ 'image/png', 'image/jpg', 'image/jpeg' ], 'pdf': [ 'application/pdf', 'application/x-pdf' ] }; function fileLoadByDefault(selector, type, block) { var input = document.getElementById(selector), formdata = false; input.click(); }
(function ($) { $(document).ready(function () { $.fn.uploadFile = function (type) { var blockText = { 'img': {'text': ['Drag Image File Here'], 'name': ['img'], 'id': ['imguploadform']} }; this.append('<p>' + blockText[type].text + '</p>'); this.append('<input type="file" class="upload-file" name="' + type + 'file" id="' + type + 'uploadform" data-type="'+ blockText[type].name +'">'); this.addClass('drag_n_drop--' + type + 'Path'); $('input', this).hide(); fileDropBlock(this, type); }; var imgBlock = $('div', 'div[id$="_coverPath"]'); imgBlock.uploadFile('img'); $('input[type="file"]').on("change", function () { var $_this = $(this), type = $_this.data('type'), reader, file; file = this.files[0]; if (window.FormData) { formdata = new FormData(); } if (window.FileReader) { reader = new FileReader(); reader.readAsDataURL(file); } if (formdata) { formdata.append("file", file); } if (!$.inArray(file.type, arrayType[type])) { $.ajax({ url: "/upload-file", type: "POST", data: formdata, processData: false, contentType: false, success: function (res) { var userData = jQuery.parseJSON(res); $_this.parent().find('input[type="text"]').val(userData.filePath); } }); } else { alert('Wrong type') } }); imgBlock.click(function () { fileLoadByDefault('imguploadform', 'img', this); }); }); })(jQuery);
$.fn.uploadFile = function (type) { var blockText = { 'img': { 'text': ['Drag Image File Here'], 'name': ['img'], 'id': ['imguploadform'] } }; this.append('<p>' + blockText[type].text + '</p>'); this.append('<input type="file" class="upload-file" name="' + type + 'file" id="' + type + 'uploadform" data-type="'+ blockText[type].name +'">'); this.addClass('drag_n_drop--' + type + 'Path'); $('input', this).hide(); fileDropBlock(this, type); };
this.append('<p>' + blockText[type].text + '</p>');
this.append('<input type="file" class="upload-file" name="' + type + 'file" id="' + type + 'uploadform" data-type="'+ blockText[type].name +'">');
this.addClass('drag_n_drop--' + type + 'Path');
$('input', this).hide();
.drag_n_drop--imgPath{ width: 150px; height: 100px; cursor: pointer; border: 2px solid #e0e0e0; background: #f9f9f9; }
var imgBlock = $('div', 'div[id$="_name"]'); # imgBlock.uploadFile('img'); # uploadFile
$('input[type="file"]').on("change", function () { # , var $_this = $(this), type = $_this.data('type'), reader, file; file = this.files[0]; # file if (window.FormData) { formdata = new FormData(); # ( js) } if (window.FileReader) { reader = new FileReader(); # reader.readAsDataURL(file); } if (formdata) { formdata.append("file", file); # } if (!$.inArray(file.type, arrayType[type])) { # $.ajax({ url: "/upload-file", # type: "POST", data: formdata, # processData: false, contentType: false, success: function (res) { var userData = jQuery.parseJSON(res); # $_this.parent().find('input[type="text"]').val(userData.filePath); # } }); } else { alert('Wrong type'); # alert } });
imgBlock.click(function () { fileLoadByDefault('imguploadform', 'img', this); });
my_file_upload: pattern: /upload-file defaults: { _controller: MyFolderMyBundle:Default:uploadFile }
<?php namespace MyFolder\MyBundle\Controller; use Symfony\Component\HttpFoundation\File\File; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\File\UploadedFile; class DefaultController extends Controller { public function uploadFileAction() { $filename = $_FILES['file']; # $uploadPath = $this->upload($filename); # /** * . */ return null === $uploadPath ? new Response(json_encode(array( 'status' => 0, 'message' => 'Wrong file type' ) ) ) : new Response(json_encode(array( 'status' => 1, 'message' => $filename, # 'filePath' => $uploadPath # ) ) ); } private function getFoldersForUploadFile($type) { $fileType = $this->returnExistFileType($type); # if ($fileType !== null) { return array( 'root_dir' => $this->container->getParameter('upload_' . $fileType . '_root_directory'), # 'dir' => $this->container->getParameter('upload_' . $fileType . '_directory'), # ); } else { return null; } } # () private function returnExistFileType($type) { $typeArray = array( 'img' => array( 'image/png', 'image/jpg', 'image/jpeg', ), 'pdf' => array( 'application/pdf', 'application/x-pdf', ) ); foreach ($typeArray as $key => $value) { if (in_array($type, $value)) { return $key; } } return null; } # . , , private function upload($file) { $filePath = $this->getFoldersForUploadFile($file['type']); if (null === $this->getFileInfo($file['name']) || $filePath === null) { return null; } $pathInfo = $this->getFileInfo($file['name']); $path = $this->fileUniqueName() . '.' . $pathInfo['extension']; $this->uploadFileToFolder($file['tmp_name'], $path, $filePath['root_dir']); unset($file); return $filePath['dir'] . DIRECTORY_SEPARATOR . $path; } # ( ) private function getFileInfo($file) { return $file !== null ? (array)pathinfo($file) : null; } # private function fileUniqueName() { return sha1(uniqid(mt_rand(), true)); } # private function uploadFileToFolder($tmpFile, $newFileName, $rootFolder) { $e = new File($tmpFile); $e->move($rootFolder, $newFileName); }
parameters: upload_img_root_directory: %kernel.root_dir%/../web/upload/img upload_img_directory: upload/img
Source: https://habr.com/ru/post/199482/
All Articles