bnbc/upload-bundle

此包已弃用,不再维护。未建议替代包。

Symfony Upload Ajax Bundle

安装数: 18,145

依赖: 0

建议者: 0

安全: 0

星标: 17

关注者: 1

分支: 8

开放问题: 4

语言:JavaScript

类型:symfony-bundle

dev-master 2020-10-27 10:48 UTC

This package is auto-updated.

Last update: 2022-07-27 14:37:30 UTC


README

此捆绑包将允许您在表单中添加AJAX上传字段。 基于blueimp/jQuery-File-Upload插件

通过composer安装

require 添加到您的 composer.json 文件中,并运行 composer update 命令

# composer.json

{
    // ...
    require: {
        // ...
        "bnbc/upload-bundle": "dev-master"
    }
}

配置

将捆绑包添加到您的kernel中

# app/AppKernel.php

// in AppKernel::registerBundles()
$bundles = array(
    // ...
    new Bnbc\UploadBundle\BnbcUploadBundle(),
    // ...
);

如果尚未由composer完成,请将位于 /vendor/bnbc/upload-bundle/Bnbc/UploadBundle/Resources/public/js 目录中的资产复制到 /web/bundles/bnbcupload/js 目录,并将JavaScript文件添加到您的模板中,如果已存在jQuery行则删除(需要jQuery 1.6+)。

<script src="{{ asset('bundles/bnbcupload/js/1_jquery.min.js') }}"></script>
<script src="{{ asset('bundles/bnbcupload/js/2_jquery.ui.widget.js') }}"></script>
<script src="{{ asset('bundles/bnbcupload/js/3_jquery.iframe-transport.js') }}"></script>
<script src="{{ asset('bundles/bnbcupload/js/4_jquery.fileupload.js') }}"></script>
<script src="{{ asset('bundles/bnbcupload/js/5_init.js') }}"></script>

添加路由

# app/config/routing.yml

bnbc_upload:
    resource: "@BnbcUploadBundle/Controller/"
    type:     annotation
    prefix:   /upload

bnbc_ajax_file 字段类型添加资源

# app/config/config.yml

twig:
    form_themes:
            - BnbcUploadBundle:Form:fields.html.twig

全局配置选项(可选)

uniqid

将所有文件名转换为uniqid
默认:false

max_file_size

文件最大大小(以字节为单位)
默认:null(则限制将取决于php.ini中的 upload_max_filesizepost_max_size 变量)
示例:10 * 1024 * 1024 = 10485760 表示(10 Mo)

accept_file_types

用于处理接受的文件或文件类型的正则表达式
默认:'/.+$/i'(允许所有文件)
示例:'/\.(gif|jpe?g|png)$/i'(仅允许gif、jpeg和png图像文件)

upload_folder

相对于web目录根的文件上传目录
默认:'uploads'
示例:'uploads/test'(可以指定子目录,它们将自动创建)

image_versions

生成额外格式,3种可能的格式: thumbnailmediumlarge。参数 crop 允许裁剪图像到指定大小
默认:null
示例

thumbnail:
    max_width: 100
    max_height: 100
    crop: true
medium:
    max_width: 300
    max_height: 300
    crop: false
large:
    max_width: 1024
    max_height: 768
    crop: false

完整示例

# app/config/config.yml

bnbc_upload:
    uniqid: true
    max_file_size: 10485760
    accept_file_types: '/\.(gif|jpe?g|png)$/i'
    upload_folder: 'uploads/test'
    image_versions:
        thumbnail:
            max_width: 100
            max_height: 100
            crop: true
        medium:
            max_width: 300
            max_height: 300
            crop: false
        large:
            max_width: 1024
            max_height: 768
            crop: false

使用方法

bnbc_ajax_file 类型字段添加到您的表单中

# Symfony 2
$formBuilder->add('myfield', 'bnbc_ajax_file');

# Symfony 3
$formBuilder->add('myfield', AjaxfileType::class);

文件字段配置选项(可选)

required

必填字段或非必填字段
默认:false

progressBar

显示进度条(图层,其宽度从0到100%)
默认:false

progressBarClass

进度条CSS类(用空格分隔)
默认: bnbc-ajax-file-progress

progressBarPosition

进度条的位置,允许使用所有jQuery插入函数
默认: append

progressElement

分配进度属性(从0到100)的元素名称:data-progress
默认:null

progressText

放置进度百分比文本的元素名称
默认:null

multiple

同时上传多个文件
默认:false

label

上传按钮标签,如果您想通过CSS自定义,则默认为:null

autoUpload

添加文件后自动上传,如果false,则会出现一个提交按钮。
默认: true

dropZone

显示拖放区域
默认: true

dropZoneText

拖放区域的文本
默认: 'Drop file(s) here'

callbackFunction

上传完成后调用的JavaScript函数名称
默认:null
示例: afterUpload
在模板中使用: var afterUpload = function(files){}; 其中 files 是上传的文件数组

formData

您可以在formData参数中为每个字段重新定义全局配置选项
默认:不设置参数

# Symfony 2
$formBuilder->add('myfield', 'bnbc_ajax_file',
    array(
        'required'            => false,
        'progressBar'         => false,
        'progressBarClass'    => 'bnbc-ajax-file-progress',
        'progressBarPosition' => 'append',
        'multiple'            => false,
        'label'               => null,
        'autoUpload'          => true,
        'dropZone'            => true,
        'dropZoneText'        => 'Drop file(s) here',
        'callbackFunction'    => null,
        'formData'            => array(
            'uniqid'            => false,
            'max_file_size'     => 5 * 1024 * 1024,
            'accept_file_types' => null,
            'upload_folder'     => 'test',
            'image_versions'    => array(
                'thumbnail' => array(
                    'max_width'  => 100,
                    'max_height' => 100,
                    'crop'       => true
                )
            )
        )
    )
);

# Symfony 3
$formBuilder->add('myfield', AjaxfileType::class,
    array(
        'required'            => false,
        'progressBar'         => false,
        'progressBarClass'    => 'bnbc-ajax-file-progress',
        ...        
    )
);

自定义“浏览”按钮的CSS代码示例

待更新...

上传文件处理示例(未优化且不一定适用于所有情况)

    /**
     * Creates a new entity.
     *
     * @Route("/new", name="admin_entity_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $entity = new Entity();
        $form = $this->createForm('AdminBundle\Form\EntityType', $entity);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush($entity);

            if($entity->getPhoto()){
                $entity->setPhoto($this->_movePhoto($entity));
            }            
            $em->flush($entity);

            return $this->redirectToRoute('admin_entity_show', array('id' => $entity->getId()));
        }

        return $this->render('AppBundle:entity:new.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView(),
        ));
    }

    # Traitement de la photo
    protected function _movePhoto($data){
        $fs = new Filesystem();

        $dir = $this->get('kernel')->getRootDir() . '/../web/uploads/';
        $coach_dir = $this->_createEntityFolder($data);

        # On déplace la photo dans le dossier
        if($photo = $data->getPhoto()){
            $ext = pathinfo($photo, PATHINFO_EXTENSION);
            $name = 'photo.' . $ext;

            # Si le fichier existe (il peut ne pas exister dans le cas d'une modification où on uploaderai pas un nouveau fichier)
            if(file_exists($dir . $photo)){
                $fs->copy($dir . $photo, $coach_dir . '/' . $name, true);
                $fs->remove($dir . $photo);
            }
            return $name;
        }
        else {
            return null;
        }
    }
    
    # Création du dossier pour accueillir l'image
    protected function _createEntityFolder($data){
        $fs = new Filesystem();
        $dir = $this->get('kernel')->getRootDir() . '/../web/data/entity/' . $data->getId();
        try {
            $fs->mkdir($dir);
        }
        catch (IOExceptionInterface $e) {
            echo "Une erreur est survenue lors de la création du dossier : ". $e->getPath();
        }
        return $dir;
    }