【问题标题】:Pass file reader data to service in Angular Js将文件读取器数据传递给 Angular Js 中的服务
【发布时间】:2017-01-17 05:55:39
【问题描述】:

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

//index.cshtml

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

// 控制器.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];

如何解决这个问题? 谢谢

【问题讨论】:

  • 您使用的是哪个后端 api..?
  • newdataundefined,因为它是在fileReader.onload 函数中 调用testAPIService.postUploadImage异步 分配的。将该异步 API 转换为 $q 服务承诺或将服务代码移动到 API 回调中。
  • 不要将文件转换为 base64 dataURL,而是考虑将文件作为二进制文件发送。 Base64 有 33% 的开销。
  • 嗨@georgeawg。你能提供一个代码示例吗

标签: angularjs filereader


【解决方案1】:

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

【讨论】:

  • 嗨@georgeawg。 vm.files[0] 对我来说是未定义的。我使用了与演示中给出的相同代码。错误是:无法获取未定义或空引用的属性“0”
  • 嗨@georgeawg,我已经像演示一样更新了我的代码。你能告诉我吗,我需要根据你的演示进行更改
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2021-01-28
  • 2016-09-01
  • 1970-01-01
  • 2016-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多