phpsymfonyimage-uploadingsymfony-2.4

move and rename file in symfony2


I am learning Symfony2, and I am trying to upload an image from a handmade form to a destination folder, but changing its name before.

I think the easiest method is with:

move_uploaded_file(actual_file, destination_with_new_name)

But I get the following error message:

ContextErrorException: Warning: move_uploaded_file(http://localhost/PublisherMyAdmin/web/app_dev.php/imagenesportadas/1.jpg): failed to open stream: HTTP wrapper does not support writeable connections in C:\xampp\htdocs\PublisherMyAdmin\src\ochodoscuatro\IntranetBundle\Controller\MaterialesController.php line 163

My code is:

$dir =  $this->getRequest()->getUriForPath('/imagenesportadas/');
$nombre = $id.".".$extension;

if (move_uploaded_file($_FILES["archivo"]["tmp_name"], $dir.$nombre)) {

    echo "Thank you for uploading your music!<br /><br />";

} else {

    echo "Your file did not upload.<br /><br />";

}

Thank you!


Solution

  • The Symfony2 way of doing this would be similar to the following:

    You can get uploaded files from the request object, by accessing the files property. Given you are in a controller context:

    // get the request object
    $request = $this->get('request');
    
    // retrieve uploaded files
    $files = $request->files;
    
    // and store the file
    $uploadedFile = $files->get('archivo');
    $file = $uploadedFile->move($directory, $name);
    

    By calling get on the FileBag object in $files, you get an instance of UploadedFile, which provides a method move, to store and rename the temporary file.

    You get the error message because you're using an HTTP location instead of a filesystem path. Try to store the files somewhere in the web/ folder, for example:

    $directory = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/imagenesportadas';