我想用AngularJS获取一个文件:
HTML:
<div ng-controller="TopMenuCtrl">
<button class="btn" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
<input type="file" ng-model="filepick" ng-change="pickimg()" multiple />
<output id="list"></output>
</div>
JavaScript的:
angular.module('plunker', ['ui.bootstrap']);
function TopMenuCtrl($scope) {
$scope.pickimg = function() {
alert('a');
};
}
如何在AngularJS onchange
函数上绑定输入文件pickimg
动作?我怎样才能操纵上传后的文件?
Angular尚不支持输入[type = file]的ng-change,因此您必须自己滚动onchange实现。
首先,在HTML中,为onchange定义Javascript,如下所示:
<input ng-model="photo"
onchange="angular.element(this).scope().file_changed(this)"
type="file" accept="image/*" />
然后在Angular控制器代码中,定义函数:
$scope.file_changed = function(element) {
$scope.$apply(function(scope) {
var photofile = element.files[0];
var reader = new FileReader();
reader.onload = function(e) {
// handle onload
};
reader.readAsDataURL(photofile);
});
};
我使用上面的方法尝试在选择新文件时加载预览图像,但是当我尝试这样做时它没有工作:
$scope.file_changed = function(element, $scope) {
$scope.$apply(function(scope) {
var photofile = element.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$scope.prev_img = e.target.result;
};
reader.readAsDataURL(photofile);
});
});
我挖了更多,发现$ scope。$ apply应该在reader.onLoad中,否则更改$ scope变量不会工作,所以我做了以下工作:
$scope.file_changed = function(element) {
var photofile = element.files[0];
var reader = new FileReader();
reader.onload = function(e) {
$scope.$apply(function() {
$scope.prev_img = e.target.result;
});
};
reader.readAsDataURL(photofile);
};
Teemu解决方案不适用于IE9。
我已经将Flash polyfill的简单角度指令放在一起,用于不支持HTML5 FormData的浏览器,你也可以收听上传进度事件。
Kua zxsw poi但是:Kua zxsw poi
https://github.com/danialfarid/ng-file-upload
控制器:
http://angular-file-upload.appspot.com/
以下是我的指令方法。
指示
<script src="angular.min.js"></script>
<script src="ng-file-upload.js"></script>
<div ng-controller="MyCtrl">
<input type="text" ng-model="additionalData">
<div ngf-select ng-model="files" >
</div>
HTML
Upload.upload({
url: 'my/upload/url',
data: additionalData,
file: files
}).then(success, error, progress);
调节器
angular
.module('yourModule')
.directive('fileChange', function() {
return {
restrict: 'A',
scope: {
handler: '&'
},
link: function (scope, element) {
element.on('change', function (event) {
scope.$apply(function(){
scope.handler({files: event.target.files});
});
});
}
};
});
使用上面的<input type="file" file-change handler="fileSelect(files)">
,这是读取本地JSON文件的完整流程:
创建指令:
fileSelect = function (files) {
var file = files[0];
//you will get the file object here
}
HTML:
Madura's answer
使用Javascript:
angular
.module('app.services')
.directive('fileChange', function() {
return {
restrict: 'A',
scope: {
handler: '&'
},
link: function (scope, element) {
element.on('change', function (event) {
scope.$apply(function(){
scope.handler({files: event.target.files});
});
});
}
};
});
这是我为解决这个问题而写的一个轻量级指令,它反映了附加事件的角度方式。
您可以像这样使用指令:
HTML
<input type="file" file-change handler="fileSelect(files)">
如您所见,您可以将选定的文件注入事件处理程序,就像将$ event对象注入任何ng事件处理程序一样。
使用Javascript
$scope.fileSelect = function(files) {
var file = files[0];
var reader = new FileReader();
reader.onload = function(e) {
console.log("on load", e.target.result);
}
reader.readAsText(file);
}
我做了一个指示。这是<input type="file" file-change="yourHandler($event, files)" />
。
该应用程序适用于选择csvs并将其显示为html表。
使用on-file-change指令,您将能够在控制器本身中定义文件读取和解析(使用服务,可能是)逻辑,这将提供更大的灵活性。只是为了注释,传递给on-file-change属性的angular
.module('yourModule')
.directive('fileChange', ['$parse', function($parse) {
return {
require: 'ngModel',
restrict: 'A',
link: function ($scope, element, attrs, ngModel) {
// Get the function provided in the file-change attribute.
// Note the attribute has become an angular expression,
// which is what we are parsing. The provided handler is
// wrapped up in an outer function (attrHandler) - we'll
// call the provided event handler inside the handler()
// function below.
var attrHandler = $parse(attrs['fileChange']);
// This is a wrapper handler which will be attached to the
// HTML change event.
var handler = function (e) {
$scope.$apply(function () {
// Execute the provided handler in the directive's scope.
// The files variable will be available for consumption
// by the event handler.
attrHandler($scope, { $event: e, files: e.target.files });
});
};
// Attach the handler to the HTML change event
element[0].addEventListener('change', handler, false);
}
};
}]);
函数将成为指令内输入更改事件的处理程序。
fiddle
ac.onFileChange
(function (angular, document) {
angular
.module("app.directives", [])
.directive("onFileChange", ["$parse", function ($parse) {
return {
restrict: "A",
link: function (scope, ele, attrs) {
// onFileChange is a reference to the same function which you would define
// in the controller. So that you can keep your logic in the controller.
var onFileChange = $parse(attrs.onFileChange.split(/\(/)[0])(scope)
ele.on("change", onFileChange)
ele.removeAttr("on-file-change")
}
}
}])
angular
.module("app.services", [])
.service("Parse", ["$q", function ($q) {
var Parse = this
Parse.csvAsGrid = function (file) {
return $q(function (resolve, reject) {
try {
Papa.parse(file, {
complete: function (results) {
resolve(results.data)
}
})
} catch (e) {
reject(e)
}
})
}
}])
angular
.module("app", ["app.directives", "app.services"])
.controller("appCtrl", ["$scope", "Parse", function ($scope, Parse) {
var ac = this
ac.fileName = ""
ac.onFileChange = function (event) {
if (!event.target.files.length) {
return
}
Parse.csvAsGrid(event.target.files[0]).then(outputAsTable)
}
ac.clearInput = function (event) {
var input = angular.element(event.target)
input.val("")
document.getElementById("output").innerHTML = ""
}
function outputAsTable(grid) {
var table = ['<table border="1">']
grid.map(function (row) {
table.push('<tr>')
row.map(function (cell) {
table.push('<td>' + cell.replace(/["']/g, "") + '</td>')
})
table.push('</tr>')
})
table.push('</table>')
document.getElementById("output").innerHTML = table.join("\n")
}
}])
})(angular, document)
使用ng-model-controller的指令:
table {
border-collapse: collapse;
}
用法:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.min.js"></script>
<div ng-app="app" ng-controller="appCtrl as ac">
<label>Select a comma delimited CSV file:-</label>
<input id="filePicker" type="file" on-file-change="ac.onFileChange(event)" ng-click="ac.clearInput($event)"/>{{ac.fileName}}
</div>
<div id="output"></div>
有关更多信息,请参阅app.directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
。