-2

I'm trying to upload file to server using jQuery and AJAX. I want handle using PHP command move_uploaded_file, but I don't now how to do it. It's possible to use this function from Symfony's controller?

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

5

In a symfony2 controller you will have access to a Request object. If you are uploading a file you should be able to handle the upload using this object:

namespace ACME\TestBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class MyController extends Controller {
    // ...
    public function handleUploadAction(Request $reuqest) {
        foreach($request->files as $uploadedFile) {
            $name = 'uploaded-file-name.jpg';
            $file = $uploadedFile->move('/uploads/directory', $name);
        }
    }
}  

A few things to notice here

  1. Symfony2 will automatically inject the Request object to your controller
  2. Take a look at this question symfony2 how to upload file without doctrine?
Community
  • 1
  • 1
Onema
  • 7,331
  • 12
  • 66
  • 102
  • The problem is that I don't want to use Symfony2 move function. I have to use move_uploaded_file function. It's possible to use ***move_uploaded_file*** the same way like you used ***move*** function in your code? – user2799026 Sep 04 '14 at 19:17
  • The method `UploadedFile::move` uses move_uploaded_file under the hood plus it checks for upload errors and will throw a proper exception if the operation fails: https://github.com/symfony/HttpFoundation/blob/master/File/UploadedFile.php#L241. Any particular reason why you want to use move_uploaded_file directly if there is a proper, well tested implementation of the functionality you need? – Onema Sep 04 '14 at 21:07