0

In an Anggular web app I have a form. I want to update a file, so I used lf-ng-md-file-input. This is the easy html:

<lf-ng-md-file-input lf-files='files' multiple> </lf-ng-md-file-input>

In my Controller, I did this:

let formData = new FormData();
angular.forEach(this.$scope.files,function(obj){
   formData.append('files[]', obj.lfFile);
});

Debugging it, I see that obj.lfFile exists:

lastModified:1473694273813
lastModifiedDate:Mon Sep 12 2016 17:31:13 GMT+0200 (ora legale Europa occidentale)
name:"test.jpg"
size:39790
type:"image/jpeg"
webkitRelativePath:""

The problem is that it doesn't append the file in my formData. It is still empty after the loop. Why?

1

1 Answer 1

1

I wrote a directive for this once, maybe it'll help you out:

DIRECTIVE:

angular.module('content')
    .directive('parFiles', files);

/* @ngInject */
function files($parse, $timeout) {

    var directive = {
        link: link,
        restrict: 'A'
    };

    return directive;

    function link(scope, element, attr) {
        var fn = $parse(attr['pirFiles']);

        element.bind('change', function (evt) {
            var files = [], fileList, i;
            fileList = evt.target.files;
            if (fileList != null) {
                for (i = 0; i < fileList.length; i++) {
                    files.push(fileList.item(i));
                }
            }
            $timeout(function () {
                fn(scope, {
                    $files: files,
                    $event: evt
                });
            });
        });
    }
}

VIEW:

 <input type="file"
        class="input-list__item"
        ng-disabled="dr.isFileUploaded"
        par-files="dr.addFiles($files)"
        required />

CONTROLLER:

function addFiles(files) {
    vm.files = files;
}
Sign up to request clarification or add additional context in comments.

5 Comments

In the directive, after the if(fileList != null) {...} I've written: let formData = new FormData(); formData.append("files", files[0]); but it cannot append the file yet. Why?
Are you sure that files actually has data??
The debug of chrome console shows me that files[0] is this: lastModified : 1473694273813 lastModifiedDate : Mon Sep 12 2016 17:31:13 GMT+0200 (ora legale Europa occidentale) name : "test.jpg" size : 39790 type : "image/jpeg" webkitRelativePath : ""
Then; shouldn't it just be formData.append('file', obj); ?
No, after the append, this is the value of formData: proto : FormData

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.