0

I'm doing a basic image upload using this code

$scope.fileChanged = function () {
    var fileuploader = angular.element("#uploadFile");   
    var reader = new FileReader();
    reader.onload = function () {
        var image = document.getElementById("image");
        image.src = reader.result;
        image.style.opacity = 1;
        $scope.image = reader.result; 
    };
    var files = fileuploader[0].files;
    reader.readAsDataURL(files[0]);
    fileuploader.trigger('click');
};

html

<input type="file" ng-show="false" id="uploadFile" accept="image/*"
       onchange="angular.element(this).scope().fileChanged()" required>

When the user selects a image file, it appears in the HTML and set's $scope.image.

Right after the user selects an image, the image is displayed on the HTML image.src = reader.result;. Works well and fast.

BUT, $scope.image = reader.result; takes like 8 seconds to execute. Why the image src set is fast but setting a simple string is slow?

Even with few KB image it takes a lot of time..

edit:

// IMAGE APPEARS VERY FAST

<img src="../../../assets/img/gamification-icon.png" id="image"
     ng-click="uploadPicture()"> 

// This takes a lot of seconds to appear

 <div class="col-md-6">{{image}}</div>
georgeawg
  • 48,608
  • 13
  • 72
  • 95
user12361681
  • 97
  • 2
  • 7

1 Answers1

0

Data URLs are obsolete because they consume time and memory.

Use Object URLs instead:

var image = document.getElementById("image");
image.src = URL.createObjectURL(files[0]);

Object URLs are much more efficient and faster.

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95