1

I'm Uploading files with AngularJS. How to get the input files just like regular JS?

This is what I need to simulate exactly
HTML:

<input type="file" name="file" id="fileImg" accept="image/*">

JS:

var filesUpload = document.getElementById("fileImg").files

This is what I have now
HTML:

<input type="file" name="file" ng-model="image" accept="image/*">
<input type="button" ng-click="submit()" value="press me">

Angular:

angular
        .module('app')
        .controller("productsCtrl", function($scope) {

            $scope.image = {};


            $scope.submit = function() {

                var filesUpload = ????????????????
            }
         }

So, how to get the "files" in the input withput using "getElementById" ?
notice - can't change nothing , only the "??????"

any help will be appreciated..
tnx

1 Answer 1

2

You can use custom directive

var app = angular.module('App', []);

app.controller('Main', function($scope, $timeout, $rootScope){
    $scope.onSubmit = function(){
        console.log($scope.file);
    }
});

app.directive('fileRead', [function () {
    return {
       scope: {
        fileRead: '='
       },
       link: function (scope, elem, attrs) {
           elem.bind('change', function (event) {
             scope.$apply(function () {
                scope.fileRead = event.target.files[0];
             });
           });
       }
    }
 }]);

usage

 <div ng-app="App">
    <div ng-controller="Main">
        <form ng-submit="onSubmit()">
            <input type="file" name="someName" file-read="file">
            <button type="submit">Submit</button>
        </form>
    </div>
 </div>
Sign up to request clarification or add additional context in comments.

4 Comments

sadly i can't use a directive. bummer, i know. thank anyway dude.
This is a nice solution, if you don't want to use directive, you can add some id to your input field, then in submit handler get files in this way . var fileElement = document.getElementById('file'); var files = fileElement.files;
it's a Constraint, not a wish of mine.
and ya the one with the ID , is not possible at this time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.