Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

get source and name of selected file with angularjs

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
            });
        }
    }
}]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...