I need to upload image and video files to the server in an Angular application using Laravel 5.1 as the back end. All Ajax requests need to go to the Laravel controller first, and we have the code there for how the file gets handled when it gets there. We have previously done normal HTML forms to submit file uploads to the controller, but in this case we need to avoid the page refresh of a form, so I am attempting this in Ajax through Angular.

What information do I need to send to the Laravel controller with Ajax that was being sent to the controller via an HTML form previously?

This is the code in the Laravel controller that handled the file information once it got there. That's what I need to figure out how to send, so I can hopefully reuse this code:

    $promotion = Promotion::find($id);
    if (Input::hasFile('img_path')){
        $path             = public_path().'/images/promotion/'.$id.'/';
        $file_path        = $path.'promotion.png';
        $delete           = File::delete($file_path);
        $file             = Input::file('img_path');
        $uploadSuccess    = $file->move($path, 'promotion.png');
        $promotion->img_path = '/images/promotion/'.$id.'/promotion.png';
    }
    if (Input::hasFile('video_path')){
        $path             = public_path().'/video/promotion/'.$id.'/';
        $file_path        = $path.'promotion.mp4';
        $delete           = File::delete($file_path);
        $file             = Input::file('video_path');
        $uploadSuccess    = $file->move($path, 'promotion.mp4');
        $promotion->video_path = '/video/promotion/'.$id.'/promotion.mp4';
    }

As you can see above, we are converting whatever file we get to a PNG with the file name promotion.png so it's easy to fetch, and we are only accepting .mp4 video format. Because of that, we don't need to worry about checking if the file exists and is it ok to overwrite it. That's why you can see in the code we delete any existing file of that name before saving.

The HTML was just an input with a type of "file:

<input type="file" id="img_path" name="img_path" class="promo-img-path" accept="image/*">

We are using Angular now so I can't just send the above through an HTML form anymore. That's what I need to figure out how to do.

We are two developers just doing our best, so I'm sure there is a better way of doing this. However before I refactor this whole thing, I'm hoping I can use Angular (or jQuery as a last resort) to just send the controller whatever file data Laravel needs in order to make the above code work. The answer may be as simple as "send a PUT to the method in that controller above, but instead of a normal JSON payload, use file info in this format and you can gather that info with..."

I would also appreciate any tips on better ways I can do this in the future.

share|improve this question
    
Best advice I can give is to not reinvent the wheel. There's plenty of existing Angular modules for file uploads - using one will usually save you a lot of grief. – Matthew Daly Jan 19 at 20:29
    
But those all upload directly somewhere - they aren't intended to send file data to a Laravel controller. – SpaceNinja Jan 19 at 20:33
    
Are you sending the files via PUT alongside regular input? – Matthew Daly Jan 19 at 20:38
    
It was being sent in a normal <form> to the above controller. Now I need to use an Ajax PUT through Angular. I just need to know how to send whatever that controller needs in a PUT, to simulate whatever gets sent from an <input type="file> like the HTML above... – SpaceNinja Jan 19 at 20:41
1  
$_FILE is the array where PHP stores any submitted files. If you're using a framework you generally don't work with it directly as the framework will usually provide another way. I would build the route for receiving the image first and make sure you can submit an image using something like Postman. Once that's done you then just have to make exactly the same request via AJAX. – Matthew Daly Jan 19 at 22:34
up vote 1 down vote accepted

How to POST FormData Using the $http Service

When using the FormData API to POST files and data, it is important to set the Content-Type header to undefined.

var fd = new FormData()
for (var i in $scope.files) {
    fd.append("fileToUpload", $scope.files[i]);
}
var config = {headers: {'Content-Type': undefined}};

var httpPromise = $http.post(url, fd, config);

By default the AngularJS framework uses content type application/json. By setting Content-Type: undefined, the AngularJS framework omits the content type header allowing the XHR API to set the content type. When sending a FormData object, the XHR API sets the content type to multipart/form-data with the proper boundaries and base64 encoding.

For more information, see MDN Web API Reference - XHR Send method


How did you get the file information into $scope.files?

I use a directive that sets the scope variable on the change event.

<input type=file my-files="files" /><br>

my-files Directive

app.directive("myFiles", function($parse) {
  return function linkFn (scope, elem, attrs) {
    elem.on("change", function (e) {
      scope.$eval(attrs.myFiles + "=$files", {$files: e.target.files});
      scope.$apply();
    });
  };
});

The DEMO on PLNKR.

share|improve this answer
    
Looks good. But for some reason the way I'm doing it the file information doesn't get appended to the FormData object so I'll try your way. I'm already doing headers: { 'Content-Type': undefined } This isn't working: angular.forEach($files, function (value, key) { formdata.append(key, value); }); How did you get the file information into $scope.files? – SpaceNinja Jan 20 at 2:36
    
I create a directive that sets the scope value on the change event. I added an old example to the answer. – georgeawg Jan 20 at 7:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.