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?
2
-
1Please read this articleBarranka– Barranka2014-09-04 18:57:35 +00:00Commented Sep 4, 2014 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– Jovan Perovic2014-09-04 23:37:30 +00:00Commented Sep 4, 2014 at 23:37
Add a comment
|
1 Answer
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?
2 Comments
user2799026
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?
Onema
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: github.com/symfony/HttpFoundation/blob/master/File/…. 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?