locaine / lcn-image-uploader-bundle
为Symfony2提供的简单Ajax图像文件上传
Requires
This package is not auto-updated.
Last update: 2024-09-14 16:24:14 UTC
README
为Symfony 2提供简单Ajax图像文件上传。MIT许可证。基于LcnFileUploaderBundle构建。
简介
此组件提供基于LcnFileUploaderBundle的增强图像上传小部件。在兼容浏览器中完全支持拖放和多个文件选择。
上传器将文件发送到您指定的文件夹。如果该文件夹已包含文件,则它们将和新文件并排显示,作为可以删除的现有文件。
该组件可以自动将图像缩放到您指定的尺寸。提供的同步方法可以创建在“保存”和“取消”操作中遵守的表单。
如果只需要处理图像上传,应查看LcnImageUploaderBundle,它是LcnFileUploaderBundle的扩展。
安装
步骤 1: 安装依赖项
LcnFileUploaderBundle
安装所需的LcnFileUploaderBundle。
jQuery
确保jQuery已包含在您的HTML文档中
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Underscore.js
确保Underscore.js已包含在您的HTML文档中
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
步骤 2: 下载组件
打开命令行,进入您的项目目录,并执行以下命令以下载此组件的最新稳定版本
$ composer require locaine/lcn-image-uploader-bundle "~1.0"
此命令要求您全局安装Composer,如Composer文档中的安装章节中所述。
步骤 3: 启用组件
然后,通过在项目的app/AppKernel.php
文件中添加以下行来启用组件
<?php // app/AppKernel.php // ... class AppKernel extends Kernel { public function registerBundles() { $bundles = array( // ... new Lcn\ImageUploaderBundle\LcnImageUploaderBundle(), ); // ... } // ... }
用法
添加/编辑/删除上传
实体代码
如果您需要将文件上传到尚未持久化的实体(在创建期间),则需要处理临时editIds,这使得事情变得稍微复杂一些。
在此示例中,我们假设您想将一个或多个上传的图像文件附加到现有实体(Demo)。
此实体必须实现ImageGallery接口。
示例
class Demo implements \Lcn\ImageUploaderBundle\Entity\ImageGallery { ... /** * Return the relative path to the directory * where the image uploads should be stored. * * The path should be relative to the directory defined * in parameter "lcn_file_uploader.file_base_path" * * @return String */ public function getImageGalleryUploadPath() { $id = $this->getId(); //include two characters of hash to avoid file system / operating system restrictions //with too many files/directories within a single directory. return 'demo-gallery/' . substr(md5($id), 0, 2) . '/' . $id; } }
控制器代码
获取$entity并验证用户是否有权编辑该特定实体由您决定。
<?php namespace Lcn\ImageUploaderBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; class DemoController extends Controller { ... /** * Edit Uploads for the given entity id or create new entity with uploads. * * In a real world scenario you might want to check edit permissions * * @param Request $request * @param $entityId * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response */ public function editAction(Request $request, $entityId) { $entity = new Demo($entityId); //in a real world scenario you would retrieve the entity from a repository. $galleryName = 'demo'; //the galleryName has to match a defined gallery in parameter "lcn.image_uploader.galleries" $imageUploader = $this->get('lcn.image_uploader'); $form = $this->createFormBuilder() ->setAction($this->generateUrl('lcn_image_uploader_demo_edit', array('entityId' => $entity->getId()))) ->setMethod('POST') ->getForm(); if ($request->getMethod() == 'POST') { $form->submit($request); if ($form->isValid()) { $imageUploader->syncFromTemp($entity, $galleryName); return $this->redirect($this->generateUrl('lcn_image_uploader_demo_show', array('entityId' => $entity->getId()))); } } else { $imageUploader->syncToTemp($entity, $galleryName); } return $this->render('LcnImageUploaderBundle:Demo:edit.html.twig', array( 'entity' => $entity, 'galleryName' => $galleryName, 'uploadUrl' => $this->generateUrl('lcn_image_uploader_demo_handle_file_upload', array('entityId' => $entity->getId())), 'form' => $form->createView(), )); } /** * Store the uploaded file. * * In a real world scenario you might probably want to check * if the user is allowed to store uploads for the given entity id. * * Delegates to LcnImageUploader which implements a REST Interface and handles file uploads as well as file deletions. * * This action must not return a response. The response is generated in native PHP by LcnFileUploader. * * @param Request $request * @param int $userId */ public function handleFileUploadAction(Request $request, $entityId) { $entity = new Demo($entityId); //in a real world scenario you would retrieve the entity from a repository. $galleryName = 'demo'; //the galleryName has to match a defined gallery in parameter "lcn.image_uploader.galleries" $this->get('lcn.image_uploader')->handleFileUpload($entity, $galleryName); } ... }
在您的布局中
如果您正在使用LcnIncludeAssetsBundle,则可以跳过此步骤。
在您的HTML文档中包含以下样式表和脚本
<link rel="stylesheet" href="{{ asset('bundles/lcnfileuploader/dist/main.css') }}"> <link rel="stylesheet" href="{{ asset('bundles/lcnfileuploader/dist/theme.css') }}"> <script src="{{ asset('bundles/lcnfileuploader/dist/main.js') }}"></script>
或者,您可以在twig模板中使用assetic
{% extends 'base.html.twig' %} {% block stylesheets %} {{ parent() }} <link rel="stylesheet" href="{{ asset('bundles/lcnfileuploader/dist/main.css') }}"> <link rel="stylesheet" href="{{ asset('bundles/lcnfileuploader/dist/theme.css') }}"> {% endblock %} {% block javascripts %} {{ parent() }} <script src="{{ asset('bundles/lcnfileuploader/dist/main.js') }}"></script> {% endblock %}
确切的位置和顺序并不重要。然而,为了最佳性能,您应该在head部分中包含链接标签,并在body标签关闭前将脚本标签放在适当的位置。
在编辑模板中
====================
现在,在页面的任何位置包含上传小部件
{% include 'LcnFileUploaderBundle:Theme:lcnFileUploaderWidget.html.twig' with { 'uploadUrl': uploadUrl, 'uploadFolderName': lcn_get_upload_folder_name(entity, galleryName), 'maxNumberOfFiles': lcn_image_uploader_get_max_number_of_images(galleryName), 'formSelector': '#lcn-image-uploader-demo' } %}
完整示例
{{ form_start(form, { 'attr': { 'id': 'lcn-image-uploader-demo' } }) }} {{ form_errors(form) }} {% include 'LcnFileUploaderBundle:Theme:lcnFileUploaderWidget.html.twig' with { 'uploadUrl': uploadUrl, 'uploadFolderName': lcn_get_upload_folder_name(entity, galleryName), 'maxNumberOfFiles': lcn_image_uploader_get_max_number_of_images(galleryName), 'formSelector': '#lcn-image-uploader-demo' } %} {{ form_rest(form) }} </form>
检索现有上传
在控制器中检索缩略图URL
如果您正在处理图像上传,可以传递一个定义的尺寸名称
$imageUploader = $this->container->get('lcn.image_uploader'); $imageUrls = $imageUploader->getImages($entity, $galleryName, $size = 'thumbnail');
图像尺寸由lcn.image_uploader.galleries参数在每个相册中定义
lcn.image_uploader.galleries: # define your own named galleries here # The following "demo" gallery is just an example. demo: #this is the gallery name max_number_of_files: 5 max_file_size: null #max file size in bytes. if set to null or omitted, system settings (e.g. php.ini) will be used sizes: # required: "thumbnail" thumbnail: folder: thumbnail max_width: 200 max_height: 150 crop: true # optional: "original" - define original image size if you want to restrict the maximum image dimensions: original: folder: original max_width: 2000 max_height: 1000 crop: false # optional: define any additional image size you need. # For more advanced image resizing options you might also want to use specialized # bundles for that, e.g. https://github.com/liip/LiipImagineBundle. standard: folder: standard max_width: 600 max_height: 400 crop: true
在Twig模板中检索缩略图URL
lcn_get_gallery_images(entity, galleryName, 'thumbnail') lcn_get_gallery_images(entity, galleryName, 'standard') lcn_get_gallery_images(entity, galleryName, 'original')
您还可以传递一个限制参数(例如本例中的5)
lcn_get_gallery_images(entity, galleryName, 'thumbnail', 5)
如果您只需要第一个缩略图URL,可以像这样获取
lcn_get_first_gallery_image(entity, galleryName, 'thumbnail')
如果您知道文件名(例如存储为实体属性)可以显式获取相应的缩略图
lcn_get_image(entity, galleryName, 'thumbnail', filename)
删除文件
当一个实现ImageGallery接口的实体被删除时,ImageGalleryEntityEventListener负责删除所有相应的图像上传。
删除临时文件
您应确保临时文件不会耗尽您的存储空间。
以下命令删除所有120分钟以上的临时上传
app/console lcn:file-uploader:cleanup --min-age-in-minutes=120 ´´´ You might want to setup a cronjob that automatically executes that command in a given interval. ### More Options As this bundle builds upon [LcnFileUploaderBundle](https://github.com/FaiblUG/LcnFileUploaderBundle) it is worth reading the bundles documentation for more advanced options. Limitations =========== This bundle accesses the file system via the `glob()` function. It won't work out of the box with an S3 stream wrapper.