【发布时间】: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..?
-
newdata是undefined,因为它是在fileReader.onload函数中在 调用testAPIService.postUploadImage内异步 分配的。将该异步 API 转换为 $q 服务承诺或将服务代码移动到 API 回调中。 -
不要将文件转换为 base64 dataURL,而是考虑将文件作为二进制文件发送。 Base64 有 33% 的开销。
-
嗨@georgeawg。你能提供一个代码示例吗
标签: angularjs filereader