如何使用 AngularJS 获取在文件资源管理器中选择的文件的 URL
How to get the URL for the file selected in File Explorer using AngularJS
我需要单击“选择文件”和 select 文件资源管理器中的文件,然后我需要获取 selected 文件的 URL 并将其存储在variable.Can 请查看下面的代码并指导我,因为我是 AnularJS 的新手...在此先感谢。
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body >
<div ng-app = "myApp" ng-controller="myControl">
<input type="file" file-model="myFile" ng-module = "file_name" ng-click = "file_name()"><br>
<h1>{{file_name()}}</h1>
</div>
<script>
var app= angular.module("myApp",[]);
app.controller("myControl",function($scope){
$scope.file_name = function(){
return $scope.file_name;
};
});
</script>
</body>
</html>
您可以创建 url
directive
。在控制器内部,您应该使用 $watch
方法来捕捉时刻,当 file_name
属性 将被分配时。在这个例子中你可以 select 图片文件,它会显示:
angular.module('app', [])
.controller('ctrl', ['$scope', function($scope) {
$scope.$watch('file_url', function(newVal, oldVal) {
if (newVal != oldVal)
console.log(newVal);
}, true)
}])
.directive('url', function() {
return {
restrict: 'A',
scope: {
url: '='
},
link: function(scope, element) {
element.on('change', function(event) {
var reader = new FileReader();
reader.onloadend = function() {
scope.$apply(function() {
scope.url = reader.result;
});
}
var file = element[0].files[0];
if (file)
reader.readAsDataURL(file);
})
}
}
})
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app='app' ng-controller="ctrl">
<img src="{{file_url}}" height="150" alt="Image preview...">
<input type="file" url='file_url'>
</div>
我需要单击“选择文件”和 select 文件资源管理器中的文件,然后我需要获取 selected 文件的 URL 并将其存储在variable.Can 请查看下面的代码并指导我,因为我是 AnularJS 的新手...在此先感谢。
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body >
<div ng-app = "myApp" ng-controller="myControl">
<input type="file" file-model="myFile" ng-module = "file_name" ng-click = "file_name()"><br>
<h1>{{file_name()}}</h1>
</div>
<script>
var app= angular.module("myApp",[]);
app.controller("myControl",function($scope){
$scope.file_name = function(){
return $scope.file_name;
};
});
</script>
</body>
</html>
您可以创建 url
directive
。在控制器内部,您应该使用 $watch
方法来捕捉时刻,当 file_name
属性 将被分配时。在这个例子中你可以 select 图片文件,它会显示:
angular.module('app', [])
.controller('ctrl', ['$scope', function($scope) {
$scope.$watch('file_url', function(newVal, oldVal) {
if (newVal != oldVal)
console.log(newVal);
}, true)
}])
.directive('url', function() {
return {
restrict: 'A',
scope: {
url: '='
},
link: function(scope, element) {
element.on('change', function(event) {
var reader = new FileReader();
reader.onloadend = function() {
scope.$apply(function() {
scope.url = reader.result;
});
}
var file = element[0].files[0];
if (file)
reader.readAsDataURL(file);
})
}
}
})
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app='app' ng-controller="ctrl">
<img src="{{file_url}}" height="150" alt="Image preview...">
<input type="file" url='file_url'>
</div>