Moh*_*med 6 javascript angularjs angularjs-forms angularjs-fileupload
单击提交按钮时如何获取文件内容。我只得到第一和第二输入。请参考摘要:
!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form novalidate>
First Name:<br>
<input type="text" ng-model="user.firstName"><br>
Last Name:<br>
<input type="text" ng-model="user.lastName">
<input type="file" ng-model="user.file">
<br><br>
<button ng-click="reset()">Submit</button>
</form>
<p>form = {{user}}</p>
<p>master = {{master}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.reset = function(){
console.log($scope.user)
}
});
</script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
您不能使用直接访问文件内容,ng-scopes但是可以使用本机JavaScript FileAPI读取文件内容。这是工作中的小提琴。我认为您想显示文件内容而不在服务器端上载它们。并不是100%清楚您想要什么,因此您可以在不上传的情况下在浏览器中获取filecontent,filesize和filename。
<div ng-controller="MyCtrl">
<input type="file" id="myFileInput" />
<br /><br />
<button ng-click="submit()">
Submit
</button>
<br /><br />
<br /><br />
<h1>
Filename: {{ fileName }}
</h1>
<h2>
File size: {{ fileSize }} Bytes
</h2>
<h2>
File Content: {{ fileContent }}
</h2>
</div>
Run Code Online (Sandbox Code Playgroud)
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.fileContent = '';
$scope.fileSize = 0;
$scope.fileName = '';
$scope.submit = function () {
var file = document.getElementById("myFileInput").files[0];
if (file) {
var aReader = new FileReader();
aReader.readAsText(file, "UTF-8");
aReader.onload = function (evt) {
$scope.fileContent = aReader.result;
$scope.fileName = document.getElementById("myFileInput").files[0].name;
$scope.fileSize = document.getElementById("myFileInput").files[0].size;;
}
aReader.onerror = function (evt) {
$scope.fileContent = "error";
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
我使用了指令来处理表单中的文件(如 joakimbl 在此处的答案中所建议的那样):
app.directive('validFile',[function() {
return {
require : 'ngModel',
scope : {format: '@', upload : '&upload'},
link : function(scope, el, attrs, ngModel) {
// change event is fired when file is selected
el.bind('change', function(event) {
console.log(event.target.files[0]);
scope.upload({file:event.target.files[0]});
scope.$apply(function() {
ngModel.$setViewValue(el.val());
ngModel.$render();
});
})
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
在你的 HTML 中
<input type="file" valid-file upload="uploadFile(file)" ng-model="file">
Run Code Online (Sandbox Code Playgroud)
这uploadFile是控制器中的一个函数,您可以在其中获取文件内容
控制器代码
$scope.uploadFile = function(element) {
$scope.user.file = element;
console.log($scope.user);
}
Run Code Online (Sandbox Code Playgroud)
请看看这个笨蛋
| 归档时间: |
|
| 查看次数: |
17365 次 |
| 最近记录: |