wootscootinboogie
wootscootinboogie

Reputation: 8695

Angular file upload happens immediately onchange

I've had a little bit of a rough go on uploading files through angular and have settled on the following solution:

$scope.uploadFile = function(files) {

        var fd = new FormData();
        //Take the first selected file
        fd.append("file", files[0]);
        console.log($scope.files);
        $http.post('../resource/editor', fd, {
            withCredentials: true,
            headers: {'Content-Type': undefined },
            transformRequest: angular.identity
        }).then(function(data){

            //this keeps the user from having to refresh the page
            DataContext.getEditors().then(function(data){
                $scope.myData = data;
            });

        }).catch(function(reason){

        });
    };

<form name="myForm" >
    <input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
    <input type="submit" ng-click="uploadFile()" value='Submit'/>
</form>

The current behavior is that as soon as the user selects a file, that file begins to upload. My intent is that on the click event of the button that user will upload the file. What am I missing to accomplish this?

Upvotes: 0

Views: 584

Answers (2)

Delta
Delta

Reputation: 851

You are calling upload file on the change of the input I would give the input a modal and pass that value to the upload file of the button click.

<form name="myForm" >
    <input type="file" name="file" ng-model="fileNames" />
    <input type="submit" ng-click="uploadFile(fileName)" value='Submit'/>
</form>

Upvotes: 0

pje
pje

Reputation: 2468

It looks like you're calling uploadFile() when your file input changes. That's why it's happening immediately. If you need to know what files are selected, add a statement to update some model data onchange:

<input type="file" name="file" onchange="$scope.files = this.files"/>

Then change your uploadFile() method so that it uses the $scope.files variable:

$scope.uploadFile = function() {
    ...
    //Take the first selected file
    fd.append("file", $scope.files[0]);
    ...
};

Hope this helps!

Upvotes: 2

Related Questions