AngularJS: upload and post photo as multi-part form data and get response

All we need is an easy explanation of the problem, so here it is.

I want to upload an image and post it to my server which should post the image further on to some API and get its response.

I could probably use view with something like:

<form ng-submit="updatePhoto(myphoto)"> 
    <p>Choose Photo:</p>
    <input type="file" ng-model="myphoto">
    <input type="submit" value="Send">
</form>

and then in the controller the function would have something like:

$http({
        method: 'POST',
        url: 'myAPIserver.php/',
        data: "myPhoto=" + photo,
        headers: {'Content-Type': 'multipart/form-data'}
});

But this is not correct and I am not sure how to accomplish this. The catch is that I am sending this photo to my PHP proxy first and from there I use curl to make direct API requests.

I hope I was clear enough. Any suggestions appreciated, thanks

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I managed to accomplish this with the help of custom directive that I got here.
You need a custom directive for file upload if you want to access files (ngModel wont work, see this for more info).

Using first link:

<form ng-submit="updateSth()" name="uploadForm" enctype="multipart/form-data">
    <input name="file" type="file" id="file" file-model="fileToUpload" />
    <input name="somethingINeed" type="submit" value="Upload" />
</form> 

you can access the uploaded file with $scope.fileToUpload now, which makes everything easier.
I extracted the function from the service given on the first link and didn’t use it as a service since it suited me better this way …

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply