AngularJS:如何通过$ resource在POST中发送图像文件?

时间:2014-11-19 14:14:57

标签: javascript angularjs http resources multipartform-data

我正在尝试使用$ resource发出HTTP请求,这将发送此邮递员请求所提供的相同信息。

以下是我需要复制的请求:

邮差要求:

enter image description here

邮递员标题:

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");
                    });
                }
            });
});

我的请求标题:我。堆栈。 imgur。 COM / 4inXR.jpg

1 个答案:

答案 0 :(得分:5)

在我的一个项目中,我使用了这个角度模块https://github.com/danialfarid/angular-file-upload。 它对我很有用,也有演示网站。