使用angularjs获取所选文件的来源和名称 [英] get source and name of selected file with angularjs
问题描述
有没有办法使用angularJS在输入字段中获取所选文件的名称、路径和大小,在上传之前?
$scope.showContent = 函数($fileContent){$scope.content = $fileContent;};
有人可以帮忙解决这个问题吗?
HTML5 文件 API 将为您尝试上传的每个文件提供一个 File
对象.这个 File
对象将有一个 size
和 name
属性,它们将为您提供文件大小(以字节为单位)和文件名称.
不过,用户计算机上文件的物理路径没有属性.
您可以在 MDN 上阅读更多相关信息:https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
有关 File
对象的更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/API/File
这是一个工作示例:http://jsfiddle.net/fmeLz9cd/
给定一个 file
类型的输入,id 为 fileSelected
,下面是一个通过 File API 访问属性的例子:
$('#fileSelected').on('change', function (evt) {var 文件 = $(evt.currentTarget).get(0).files;如果(文件.长度> 0){$('#fileName').text(files[0].name);$('#fileSize').text(files[0].size);$('#filePath').text($('#fileSelected').val());}});
更新
由于您请求了一个 AngularJS 特定示例,以下是在 Angular 应用程序中工作的相同代码:
http://jsfiddle.net/vyc6jq84/1/
<input type="file" fd-input/>var app = angular.module('fileDemo', []);app.directive('fdInput', [function () {返回 {链接:函数(范围、元素、属性){element.on('change', function (evt) {var 文件 = evt.target.files;控制台.日志(文件[0].名称);控制台日志(文件[0].大小);});}}}]);
Is there a way to get name, path and size of selected file in input field using angularJS, before uploading it?
<input type="file" ng-model="fileContent" on-read-file="showContent($fileContent)" />
$scope.showContent = function($fileContent){
$scope.content = $fileContent;
};
Can anyone help to solve this please?
The HTML5 File API will give you a File
object for each file that you're attempting to upload. This File
object will have a size
and name
property which will give you the file size in bytes and the name of the file.
There's no property for the physical path to the file on the users machine, though.
You can read more about this on MDN: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
More information on the File
object here: https://developer.mozilla.org/en-US/docs/Web/API/File
Here's a working example: http://jsfiddle.net/fmeLz9cd/
Given an input of type file
with an id fileSelected
, here's an example of accessing the properties through the File API:
$('#fileSelected').on('change', function (evt) {
var files = $(evt.currentTarget).get(0).files;
if(files.length > 0) {
$('#fileName').text(files[0].name);
$('#fileSize').text(files[0].size);
$('#filePath').text($('#fileSelected').val());
}
});
Update
Since you've requested an AngularJS specific example, here's the same code working in an angular app:
http://jsfiddle.net/vyc6jq84/1/
<div ng-app="fileDemo">
<input type="file" fd-input />
</div>
var app = angular.module('fileDemo', []);
app.directive('fdInput', [function () {
return {
link: function (scope, element, attrs) {
element.on('change', function (evt) {
var files = evt.target.files;
console.log(files[0].name);
console.log(files[0].size);
});
}
}
}]);
这篇关于使用angularjs获取所选文件的来源和名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!