问题
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
<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);
});
};
});
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
回答1:
Uploading Files with 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
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();
});
};
});
The DEMO on PLNKR.
来源:https://stackoverflow.com/questions/41689924/pass-file-reader-data-to-service-in-angular-js