First, using the fantastic work of Jenny Louthan of Uncorked Studios, implement this directive:
|
Directives.directive('fileModel', ['$parse', function ($parse) { return { restrict: 'A', link: function(scope, element, attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function(){ scope.$apply(function(){ modelSetter(scope, element[0].files[0]); }); }); } }; }]); |
Secondly, write the Angular function to handle the upload:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
$scope.uploadImage = function (image, event) { var url = '/path/to/upload'; var formData = new FormData(); formData.append('image', image); $http.post(url, formData, { transformRequest: angular.identity, headers: { 'Content-Type': undefined } }) .success(function(data) { //@TODO: something unique here to properly display a success message. }) .error(function(data) { //@TODO: something unique here for an error message alert(data.message); }); }; |
Third, write the action in Symfony to process the file upload, with the proper route: path/to/routes.yml
|
image_upload_route: path: /path/to/upload defaults: { _controller: Path\To\Controller:imageUpload } |
path/to/MyController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
public function imageUploadAction(Request $request) { try { $image = $request->files->get('image'); if(!$image instanceof UploadedFile) { throw new InvalidFormException(sprintf('Image must be of type UploadedFile, %s given.', get_class($image))); } //$image is now an instance of Symfony\Component\HttpFoundation\File\UploadedFile //@TODO: process your image here. $responseData = array( 'message' => '', ); $response = new Response($responseData); $response->headers->set('Content-Type', 'application/json'); return $response; } catch(\Exception $e) { throw $e; } } |
Now, referencing my previous post on setting up Liip + Read more…