Giter VIP home page Giter VIP logo

vichuploaderbundle's Introduction

VichUploaderBundle

Build Status Total Downloads Latest Unstable Version Latest stable Version

The VichUploaderBundle is a Symfony bundle that attempts to ease file uploads that are attached to ORM entities, MongoDB ODM documents, or PHPCR ODM documents.

  • Automatically name and save a file to a configured directory
  • Inject the file back into the entity or document when it is loaded from the datastore as an instance of Symfony\Component\HttpFoundation\File\File
  • Delete the file from the file system upon removal of the entity or document from the datastore
  • Templating helpers to generate public URLs to the file

All of this functionality is fully configurable to allow for app-specific customization.

Documentation

For usage documentation, see:

docs/index.md

If upgrading from a previous version, also check:

UPGRADE.md

Contributing

See the CONTRIBUTING file.

License

See the bundled LICENSE file.

vichuploaderbundle's People

Contributors

benr77 avatar bobvandevijver avatar bocharsky-bw avatar dragnucs avatar dustin10 avatar emmanuelvella avatar endelwar avatar foaly-nr1 avatar ftassi avatar garak avatar gelolabs avatar gido avatar ionbazan avatar javiereguiluz avatar jbafford avatar jmontoyaa avatar k-phoen avatar kbond avatar khepin avatar koc avatar mvhirsch avatar oleg-andreyev avatar pierre-h avatar restless-et avatar stfalcon avatar tgabi333 avatar tgalopin avatar vincentlanglet avatar wouterj avatar zerkalica avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vichuploaderbundle's Issues

remove previous file when entity updated

when we change the file attached, the previous file is not changed.
I created a listener on preUpdate doctrine event to do it but it will should be better if it was automatic thanks to the uploaderbundle ?

How can I update a image?

I need help, I am trying updated a image which exist in my project.

But I don't get do nothing.

Somebody can show a example of updated controller with this bundle ??

Thanks you very very very much!

Here I show my code:

public function modifieImageAction()
    {
        $em = $this->getDoctrine()->getManager();
        $peticion = $this->get('request');

        $u  = $this->get('security.context')->getToken()->getUser();
        $image = $u->getImage();

        $form = $this->get('form.factory')->create(new ImageType());
        $form->setData($image);

        if('POST' == $peticion->getMethod())
        {
            $form->bindRequest($peticion);

            if($form->isValid()){
                $em = $this->getDoctrine()->getManager();

                $foto = new Foto();
                $foto->setImage($form->getData()->getImage());

                $foto->setUser($u);
                $em->persist($foto);

                $u->setImage($image);
                $em->persist($u);
                $em->persist($fotoPerfil);
                $em->flush();
            }
        }
        return ($this->render('UserBundle:Profile:modifyImageProfile.html.twig' ,
                array(
                        'u' => $u,
                        'form' => $form->createView()
                )));
    }

My ImageType is:


public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('imageName')
        ->add('image', 'file', array(
                    'data_class' => 'Symfony\Component\HttpFoundation\File\File',
                    'property_path' => 'image',
                    'required' => true,
                ))
        ;
    }

    public function getDefaultOptions(array $options)
    {
        return array(
        'data_class' => 'project\FotoBundle\Entity\Foto'
        );
    }

    public function getName()
    {
        return 'ImageType';
    }
}

Uploading two fields

When i try to upload two files, both in the same entity, but different fields, one is saved correctly and moved into the web directory, but the other is save temporarily in windows temp directory.

How do I fix this? thanks

Consider moving completely to Gaufrette

Just for discussion.
I think this makes sense.

  • Using FilesystemStorage duplicates functionality of Gaufrette and lacks flexibility.
  • gaufrette:true in config is ugly
  • With gaufrette it's not possible to use upload_destination

Gaufrette storage doesn't work with Amazon S3

When uploading a file Vich\UploaderBundle\Storage\GaufretteStorage::doUpload class throws FileNotFound exception.
Probably line 84

$dst->open(new StreamMode('ab+'));

should be

$dst->open(new StreamMode('wb+'));

"The object is not uploadable"

Hi,

I have used VichUploaderBundle with MongoDB

The upload worked fine but when i wanna use this :

in my Document :

 /**
 * @MongoDB\File
 *
 * @Vich\UploadableField(mapping="template_file", fileNameProperty="name")
 *
 * @var File $file
 */
public $file;

in my controller :

$helper = $this->container->get('vich_uploader.templating.helper.uploader_helper');
$path = $helper->asset($template, 'file');

And i get a "The object is not uploadable" any idea why the ReflectionClass is not accepted as uploadable ?

Thanks

Only works 1 time...

Hello,
I'm having a strange problem with this bundle. When I create a new record I can upload a file but it doesn't work anymore. Then I try to upload another file for the same record and nothing happens.
I'm using SonataAdminBundle. Can you help me please?
Thanks.

Tag latest version

After the recent fixes, a new version should be tagged to avoid relying on dev-master

non-existent parameter

Hello. Don't know if is this the right place where to add this issue but haven't found other.

I've just switched to @ftassi repo git://github.com/ftassi/VichUploaderBundle.git in my deps and run bin/vendors install.

I get this message :

[Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException]
The service "vich_uploader.storage.adapter.rackspace_cloud_files" has a dependency on a non-existent parameter "vich_uploader.storage.adapter.rackspace.media_container".

I've opened storage.xml and I've found
%vich_uploader.storage.adapter.rackspace.media_container%

That is not defined anywhere.

I don't need CDN storage. Is this a bug or am I missing something ?

Thanks

Symfony's form component cleanup.

After upgrading to newest version of symfony's master branch, I get following error on forms using this bundle

The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, 
but is an instance of class Symfony\Component\HttpFoundation\File\File. 
You can avoid this error by setting the "data_class" option 
to "Symfony\Component\HttpFoundation\File\File" or by adding a view 
transformer that transforms Symfony\Component\HttpFoundation\File\File to 
scalar, array or an instance of \ArrayAccess.

Is anyone planning to make PR for this issue ?

XML database definition format

Hi all,

I'm new to the Symfony, so please forgive me if I'm asking about something trivial.

I use xml to describe database schema - as far as I know in this case I cannot use annotated PHP entity class definitions, because bundle can accept only one metadata definition format - see http://symfony.com/doc/current/book/doctrine.html#book-doctrine-adding-mapping. VichUploaderBundle uses annotations to describe the uploadable fields and it does not work for me. Is there any workaround? Or how I can define the uploadable fields using xml?

Thank you much,
Seb

upload multiplefile?

config

articolo_image :

uri_prefix: /images/foto_user

        upload_destination: %kernel.root_dir%/../web/images/
        delete_on_remove: true
        namer: namer.articolo_image
        inject_on_load: true 
        directory_namer: directory_namer.directory_articolo_image

entity

/**
* @Assert\File(
* maxSize="1M",
* mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
* )
* @vich\UploadableField(mapping="articolo_image", fileNameProperty="imageName")
*
* @var File $image
*/
public $image;

/**
 * @ORM\Column(type="string", length=255, name="image_name")
 *
 * @var string $imageName
 */
public $imageName;

/**
 * @Assert\File(
 *     maxSize="1M",
 *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
 * )
 * @Vich\UploadableField(mapping="articolo_image", fileNameProperty="imageName2")
 *
 * @var File $image2
 */
public $image2;

/**
 * @ORM\Column(type="string", length=255, name="image_name2")
 *
 * @var string $imageName2
 */
public $imageName2;

the first image upload, the second no

The file "/tmp/phpU80tU6" does not exist

The Gaufrette integration breaks DirectoryNamer

The DirectoryNamer interface used to get the upload directory as it's third parameter, now that variable only contains the name of the Gaufrette FS in use.

Returning a relative path does not work when asking the directory to be created either.

Change behaviour on entity update

Hi, I am using same FormType for new/edit and the problem is when i try to update an entity, the file input is being shown but no file is being uploaded. The bundle should recognize if there is no file uploaded

Warning: Missing argument 1 for Symfony\Component\HttpFoundation\File\File::__construct(), called in 
/var/www/project/Symfony/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/Type/FormType.php 
on line 161 and defined in /var/www/project/Symfony/vendor/symfony/symfony/src/Symfony/Component
/HttpFoundation/File/File.php line 38 

Other problem I noticed is that if i try to upload new file, nothing happens.

writing fixtures

I experement somme issues when writing fixtures using DoctrineFixturesBundle
who i can handle this ?

Show a image in a template twig. ?!?!

I have the same problem that issue #24.

In my twig template I have:

<img src="{{ vich_uploader_asset(user.image, 'image') }}" alt="{{ user.imageName }}" />

The image is a field of entity User:

/**
     * @ORM\Column(type="string", length=255, name="image_name")
     */
    public $imageName;
    /**
     * @Assert\File(
     *     maxSize="200k",
     *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
     * )
     * @Vich\UploadableField(mapping="imagen_perfil", fileNameProperty="imageName")
     *
     * @var File $image
     */
    protected $image;

Somebody could help me?
Thanks!

Not working with proxy objects

Unless the proxy's data has been loaded first, using the template helper will not trigger the hydration of the object and therefore the image's path will be wrong.

Annotations

I suppose that annotations could be created to do the mappings. Look into this.

variables in upload dir

Hi, let's say I want to keep separate upload folders for users (by id), and I have this config.yml:

vich_uploader:
    db_driver: orm
    mappings:
        user_profile_image:
            upload_dir: %kernel.root_dir%/../web/uploads/user_profiles

My aim is to have many folders inside user_profiles, named for example by id:

[...]/user_profiles/1/
[...]/user_profiles/2/
[...]/user_profiles/4/
[...]/user_profiles/5/
[...]/user_profiles/10/
...

created automatically passing some parameter somewhere. is it achievable?

Unable to find the wrapper "gaufrette"

Hi,

I've made a blog bundle with two entities : Article and Thumb.
The entity Thumb uses @vich\Uploadable ans is One to One related with an article
When creating/modifying a new article, you have to choose a thumb in the ArticleForm :
$builder->add('thumb', 'entity', array(
'class' => 'AcmeBlogBundle:thumb',
'property' => 'thumbname',
'multiple' => false,
'required' => false,
));
And when I send the form i have this error "Warning: file_exists() [function.file-exists]: Unable to find the wrapper "gaufrette" - did you forget to enable it when you configured PHP? in C:\wamp\www\Symfony\vendor\symfony\src\Symfony\Component\Validator\Constraints\FileValidator.php line 67 "

Uploading/Editing/Deleting thumbs works perfectly, but persisting this OneToOne relation doesn't work.

Do you have any solutions ?

Thanks, Bye !

Edit: And here is my config

knp_gaufrette:
adapters:
thumb_adapter:
local:
directory: %kernel.root_dir%/../web/img/Uploads/Thumbs
filesystems:
thumb_image_fs:
adapter: thumb_adapter

vich_uploader:
db_driver: orm
storage: vich_uploader.storage.gaufrette
mappings:
thumb_image:
uri_prefix: /img/Uploads/Tumbs
upload_destination: thumb_image_fs

Enable lifecycleCallbacks in my entity

I guess I've followed all the instructions as mentioned in the Readme file, but only got it to work when in my entity I enabled the lifecycle callbacks, adding, just before the @vich\Uploadable, the comment @Orm\HasLifecycleCallbacks. I'm using the 2.1-dev version of Symfony with Doctrine 2.2.1 ORM. Maybe this will be helpful to someone or a way to someone let me know if I did something wrong. If I am right, documentation should be updated.

Problem with User in FOSUserBundle

Hello.
I have a field image in my entity User.php

But when I want edit my email with FOsUserBundle I got the error:

The file is not found.

My field image into User entity is:

/**
     * @ORM\Column(type="string", length=255, name="image_name", nullable=true)
     */
    public $imageName;
    /**
     * @Assert\File(
     *     maxSize="200k",
     *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
     * )
     * @Vich\UploadableField(mapping="imagen_perfil", fileNameProperty="imageName")
     *
     * @var File $image
     */
    protected $image;

In my config.yml is:

vich_uploader:
    db_driver: orm
    gaufrette: false
    storage: vich_uploader.storage.file_system 
    mappings:
        product_image:
            uri_prefix: /workspace/chateagratis/web/uploads/perfil
            upload_destination: %kernel.root_dir%/../web/uploads/fotos 
        imagen_perfil:
            uri_prefix: /workspace/chateagratis/web/uploads/perfil
            upload_destination: %kernel.root_dir%/../web/uploads/perfl

Not compatible image field in the user entity with FOSUserBundle?

Problem With Directory Namer

i try to some test with directory namer

my config
http://pastebin.com/c6aXMkMg

my services

services:
namer.property_image:
class: Acme\FotoBundle\Namer\Namer
tags:
- { name: namer }
directory_namer.product:
class: Acme\FotoBundle\Namer\DirectoryNamer
tags:
- { name: directory_namer }

directorynamer.php

public function directoryName($obj, $field, $uploadDir) {

    return $uploadDir = 'ciaociao';
}

return this error

No filesystem register for name "ciaociao"
???why?

Tests

Tests need to be rewritten for the new implementation.

couldn't save the uploaded files

I just got a huge confusion that I fully followed the instruction, and there is none error during the form submission.
However as a result, there is none files lies in related configured destination, but the tmp path has been saved into
db field, like "tmp\php96F6.tmp",why?

Listener events never called

Just tried updating to symfony 2.1, I also probably was a little bit behind on this bundle, so there seemed to be one difference in config: upload_dir replaced by upload_destination.

However it seems that now the listener events are never called. I changed all the listener functions to just die('listener called') but this never seems to be triggered.

My config now reads:

vich_uploader:
    db_driver: mongodb
    storage: vich_uploader.storage.file_system
    mappings:
        league_thumbnail:
            upload_destination: %kernel.root_dir%/../web/uploads/leagues/photos
            namer: mashup.upload_namer
            inject_on_load: false
        # ...

Any ideas why this is happening?

Serialization of '...File' is not allowed when saving

I followed the documentation. But when saving I get the error:

Exception: Serialization of 'Symfony\Component\HttpFoundation\File\File' is not allowed

and

Exception: Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::serialize() must return a string or NULL

When I remove the VichUploader Assertion

@Vich\UploadableField(mapping="organization_logo", fileNameProperty="headerLogoName")

then everything the error disappears and saving works. That's why I post this problem here. I googled a little bit and found, that other persons having similar problems, but not mentioning this Bundle.

Here are extracts of my code:

// Entity


    /**
     * @Assert\File(
     *     maxSize="1M",
     *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
     * )
     *@Vich\UploadableField(mapping="organization_logo", fileNameProperty="headerLogoName")
     *
     * @var File $image
     */
    protected $headerLogo;

    /**
     * @ORM\Column(type="string", length=255, name="header_logo_name")
     *
     * @var string $headerLogoName
     */
    protected $headerLogoName;



// form

$builder->add('headerLogoName', 'file');
# config
knp_gaufrette:
    adapters:
        organization_adapter:
            local:
                directory:  %acme.media_dir%/images/organization

    filesystems:
        organization_logo_fs:
            adapter:    organization_adapter


vich_uploader:
    db_driver: orm
    gaufrette: true
    storage: vich_uploader.storage.gaufrette
    mappings:
        organization_logo:
            uri_prefix: /images/organization/logo/
            upload_destination: organization_logo_fs

Thanks for any helps and thoughts

unlink warning

I have VichUploader installed with

vich_uploader:
    db_driver: orm
    mappings:
        product_image:
            upload_dir: [my_dir]
            delete_on_remove: true    [this is the point]

scenario:

  • I upload a file attached to an entoty
  • I remove the file from the filesystem manually (e.g. console)
  • I remove the entity via symfony

at this point it gives me:

Warning: unlink([file_path]) [<a href='function.unlink'>function.unlink</a>]: No such file
or directory in
[my_site]/vendor/bundles/Vich/UploaderBundle/Storage/FileSystemStorage.php line 68

because it tries to unlink a non-existing file via

unlink(sprintf('%s/%s', $mapping->getUploadDir(), $name));

and gives correctly a warning.

I think this should be silent, if the file is not found it shouldn't raise any warning or error

maybe a try/catch would be a solution? instead of (file_exists && !is_dir)

try {
    unlink(sprintf('%s/%s', $mapping->getUploadDir(), $name));
catch (\Exception $e) {}

Tag latest version

After the recent fixes, a new version should be tagged to avoid relying on dev-master

Delete file on update

There is a "delete_on_remove" option in the config which works perfectly. However, it would be cool to also have a "delete_on_update" option which deletes the old file when it is overwritten by another one.

Right now, if I create an item with a file and then attach another image to the item, the old file stays in the file system.

add the generated id to the filename

By now it's not possible to give the Document (or Entity) a filename with the generated id. This is because the events is prePersist.

Are there any problems by changing prePersist to postPersist? (preUpdate is fine)
I could send you a PR. Maybe we should also add a parameter to let the user decide which lifecycle callback to use, and default to prePersist, so it won't break compatibility.

Let me know....

The file is not updated if there are not other changes in the entity

Say if i have a already existing record, and i'm trying to update it, in case if i ONLY upload file and no other entity properties get changed, the preUpdate event is not called, so the file is not uploaded.

Currently the workaround is to introduce some changes into the entity, before saving it.

directory namer problem

public function directoryName($obj, $field, $uploadDir) {
$nameCategoria = $obj->idCategoria->name;
$idArticolo = $obj->id;
$idUser = $obj->id_mittente->id;
return $upload = $uploadDir.'/'.$nameCategoria.'/'.$idArticolo.'/'.$idUser;

}

why curret id of object($idArticolo) is empty?

how to use custom namer

hi, i'm try your bundle, but i don't understand how to use custom namer.

Can you explain how to implement a custom namer , or show an example for a custom namer.

thanks for help.

Sorry for my english,

Multiply files uploaded in 1 entity + couple general ideas

Nice bundle, I was though about creating exactly the same functionality.

I would suggest you to create request for adding link to your bundle on
http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html

More exposure = more contributors/testers = better for all symfony2 developers :)

Another idea = moving this bundle into FOS namespace (it seems to be pretty common task).

Right now as I see bundle doesn't support multiply files uploaded for single entity.

For example, my entity video have fields screenshot and videofile.

Just wonder if you have plans of adding such a functionality :)

Going to schedule task for myself - maybe I will be able to do pull request with that functionality after holidays (not sure that I have enough symfony2 knowledges though) :)

writing fixtures

config:
...
 mappings:
        product_image:
           uri_prefix: /images/products
            upload_destination: %kernel.root_dir%/../web/images/products

Entity:

     /**
     * @Vich\UploadableField(mapping="product_image", fileNameProperty="productImage")
     */
    protected $file;

I try this:

use    Symfony\Component\HttpFoundation\File\File;
....
        $path = '/tmp/someImage.jpg';
        $imageFile = new File($path);
        $entity->setFile($imageFile);

but it does not work :(

Any ideas?

Support for Symfony2.2

Since the master of Symfony now has new and exciting features (hostname routes) it will be really nice if we can have this supporting Symfony2.2.

Thanks!

Multiple file documentation

I've read that this bundle support multiple file handling using annotation but I can't find any example or documentation about it.

incompatibility with Gaufrette.

Hello.

I have a problem. Today I did composer update
And the VichUploaderBundle doesn't work.

I get the following error:

Fatal error: Class 'Gaufrette\FileStream\Local' not found in /var/www/workspace/chateagratis/vendor/vich/uploader-bundle/Vich/UploaderBundle/Storage/GaufretteStorage.php on line 60

I saw the code and I found a problem with Gaufrette Bundle.

I have the following composer update:

"vich/uploader-bundle": "dev-master",
        "knplabs/gaufrette": "dev-master",

To solve this problem, I had to modify the line 60 of file: Vich\UploaderBundle\Storage

$src = new Local($file->getPathname());
        $dst = $adapter->createStream($name);

And the following use:

use Gaufrette\Stream\Local;

: )

VichUploader + Translatable extension

I am using your bundle to handle the upload. My entity has different images depending on the current locale, this is handled by doctrine extensions. The only problem is that only the temp path is saved in the translations, the file is not saved to the upload folder and the "fileName" field is not saved in the translations.

Do I have to write a post-(save/update/something) for this to work ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.