Dejan Skorupan
Dejan Skorupan

Reputation: 35

AngularJS: How do I send an image file in POST via $resource?

I am trying to make a HTTP request using $resource, that will send the same information this postman request does.

Here is the request I need to replicate:

Postman request:

enter image description here

Postman Headers:

enter image description here

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>File Upload</title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="lib\ionic\js\angular-file.js"></script>
    <script src="lib\ionic\js\angular-resource.js"></script>
  </head>
  <body ng-app="starter" ng-controller="FileController">
    <input type="file" ng-model="model.image" change="upload(model)"/>
  </body>
</html>

controllers.js

angular.module('starter.controllers',[])

.controller('FileController', function ($scope, $resource) {
    var Files = $resource('http://api.artistappz.com/api/v1/cover/x-app-id/3865f620590f40d493ec8d900b4c24d3/', null, {
        post: {
            method:'POST'
        }
    });

            angular.extend($scope, {

                model: { image: null },

                upload: function(model) {
                    console.log("File chosen");
                    console.log(model);
                    Files.prototype.$post.call({},model.image, function(self, headers) {
                        // Handle server response
                        console.log("DONE");
                    });
                }
            });
});

Headers from my request: i . stack . imgur . com/4inXR.jpg

Upvotes: 2

Views: 7971

Answers (1)

qwetty
qwetty

Reputation: 1268

In one of my project I use this angular module https://github.com/danialfarid/angular-file-upload. It works for me very well, also there is demo site.

Upvotes: 5

Related Questions