将文件读取器数据传递给Angular Js中的服务

时间:2017-01-17 05:55:39

标签: angularjs filereader

我正在使用文件阅读器来获取文件上传的数据。我能够在controller.js中获取数据,但无法将其传递给API服务。数据始终作为空传递。我更新了以下代码:

// index.cshtml

 <input type="file" my-files="files" />
 <input type="button" name="imageUploadButton" ng-click="uploadFiles()" value="Upload" />

// controller.js

angular.module('myApp.controllers', []).
controller('AppController', function($scope, testAPIService, Excel, $timeout, $window, $location, $anchorScroll,$http) {


var url = "server/UploadImage/";

var config = {
        headers: {
            "Content-Type": undefined,
        }
    };


 $scope.uploadFiles = function () {   


           var file = $scope.files[0];

        $http.post(url, file, config).then(function (response) {
             $scope.result = "SUCCESS";

             $scope.data = response.data.data;
         }).catch(function (response) {
             alert( "ERROR " + response.status);
         });
    };


});

angular.module("myApp.controllers").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();
            console.log(scope);
        });
    };
});

angular.module("myApp.controllers").directive("xdHref", function () {
    return function linkFn(scope, elem, attrs) {
        scope.$watch(attrs.xdHref, function (newVal) {
            newVal && elem.attr("href", newVal);
        });
    };
});

选择文件后,调用“myFiles”指令,我可以在控制台中看到数据。当我点击上传按钮时,下面的行将显示错误

var file = $scope.files[0];

如何解决这个问题? 感谢

1 个答案:

答案 0 :(得分:0)

使用AngularJS上传文件

  vm.upload = function() {
    $http.post(url, vm.files[0], config).
     then(function(response) {
      vm.result = "SUCCESS";
    }).catch(function(response) {
      vm.result = "ERROR "+response.status;
    });
  };

HTML

<input type=file my-files="files" /><br>
<button ng-click="upload()">Upload</button><br>

my-files指令

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

DEMO on PLNKR