将文件阅读器数据传递到Angular Js中的服务 [英] Pass file reader data to service in Angular Js

查看:76
本文介绍了将文件阅读器数据传递到Angular Js中的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using file reader to fetch the data of file upload. I am able to get the data in controller.js, but not able to pass it to the API service. The data is always passed as empty. I have updated the code as below:

//index.cshtml

//index.cshtml

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

//controller.js

// 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"指令被调用,且i可以在控制台看到的数据.当我单击上传"按钮时,以下一行显示为错误

When the file is selected, "myFiles" directive is invoked, and i can see the data in console. When i click on the upload button, the below line is coming as error

var file = $scope.files[0];

如何解决此问题? 谢谢

How to fix this? Thanks

推荐答案

使用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指令

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

在PLNKR上进行演示.

这篇关于将文件阅读器数据传递到Angular Js中的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆