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?
Asked
Active
Viewed 2,446 times
-2
-
1[Please read this article](http://whathaveyoutried.com) – Barranka Sep 04 '14 at 18:57
-
Tried once - few years ago when I was at very beginning of Symfony2. It was headache and I got burned up pretty good :(. So, no, avoid that at all costs... – Jovan Perovic Sep 04 '14 at 23:37
1 Answers
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
- Symfony2 will automatically inject the Request object to your controller
- Take a look at this question symfony2 how to upload file without doctrine?
-
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