Custom name & custom directory - OneupUploaderBundle

1k Views Asked by At

I am using OneupUploaderBundle with jQuery File Upload for uploads photos in my SF2 application.

By reading the doc here : https://github.com/1up-lab/OneupUploaderBundle simple upload is working and every pics I upload are stored under the /web/uploads/gallery folder with a unique generated name (uniqid() I guess)

What I want to do is : change the folder and/or the name of the file according to what a user has selected in a form (Choices come frome a select dropdown) .

This require :

But the point is that I don't know how to get what user selected in my namer or change the upload directory, can you help me please ?

Thanks

Front-END JS :

<script type="text/javascript">
$(function () {
    'use strict';
    // Change this to the location of your server-side upload handler:
    var url = '{{ oneup_uploader_endpoint('gallery') }}';
    $('#fileupload').fileupload({
        url: url,
        dataType: 'html',
        done: function (e, data) {
            console.log(data);
            $.each(data.result.files, function (index, file) {
                $('<p/>').text(file.name).appendTo('#files');
            });
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .progress-bar').css(
                'width',
                progress + '%'
            );
        }
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');
});

Listener :

namespace Acme\PhotoBundle\EventListener;

use Oneup\UploaderBundle\Event\PostPersistEvent;
use Acme\PhotoBundle\Entity\Photo;
use Symfony\Component\HttpFoundation\Response;

class UploadListener
{
protected $manager;

public function __construct($doctrine)
{
    $this->manager = $doctrine;
}

public function onUpload(PostPersistEvent $event)
{
    $file = $event->getFile();
    $response = $event->getRequest();

    $object = new Photo();
    $object->setOriginal($file->getPathName());

    var_dump($response);enter code here
    //$this->manager->persist($object);
    //$this->manager->flush();
}
}
1

There are 1 best solutions below

2
On

You can create a custom namer which will be used not only to name the file but also to create a dynamic folder structure. Take a look at this issue in the tracker.

namespace AppBundle\Uploader\Naming;

use Oneup\UploaderBundle\Uploader\File\FileInterface;
use Oneup\UploaderBundle\Uploader\Naming\NamerInterface;

class CatNamer implements NamerInterface
{
    public function name(FileInterface $file)
    {
        $product = //...
        return sprintf('%d/%s', $product->getId(), grumpycat.jpg);
    }
}

As this is a service, you can add request_stack as a parameter and create a directory structure based on the choices your users submit.