0

I have just inherited some code which loads an image locally, displays it and creates a byte array (with the intention of later uploading it). The code is the following:

       $scope.uploadFile = function (input) {
           if (input.files && input.files[0]) {
               var reader = new FileReader();
               $scope.inputID = input.id;
               reader.onload = $scope.imageIsLoaded;
               $scope.imageName = input.files[0].name;
               reader.readAsDataURL(input.files[0]);
           }
       };
       $scope.imageIsLoaded = function (e) {
           $scope.$apply(function () {
               var index = parseInt($scope.inputID.substring('photo-upload'.length));
               $('#imagenSeleccionada' + index).attr('src', e.target.result);

               //Create a canvas and draw image on Client Side to get the byte[] equivalent
               var canvas = document.createElement("canvas");
               var imageElement = document.createElement("img");

               imageElement.setAttribute('src', e.target.result);
               canvas.width = imageElement.width;
               canvas.height = imageElement.height;
               var context = canvas.getContext("2d");
               context.drawImage(imageElement, 0, 0);
               var base64Image = canvas.toDataURL("image/jpeg");

               $scope.materiales[index].Imagen = base64Image.replace(/data:image\/jpeg;base64,/g, '');
               $scope.materiales[index].NombreImagen = $scope.imageName;
               $scope.imageName = null;
           });
       }

This code works almost fine in Firefox and Microsoft Edge, but not in Chrome. In Chrome, imageElement.width and imageElement.height are both 0, so then, when doing canvas.toDataURL("image/jpg"), it returns "data:," instead of returning the byte array.

Is this a known issue? Is the code wrong?

MikMik
  • 3,426
  • 2
  • 23
  • 41
  • Probably it could be CORS issue. In Chrome Dev Tools see Network tab, if a requested image was loaded without fail. If it isn't, then need to put `access-control-allow-origin:*` or specify a domain on the server side where images are hosted – Roman Apr 25 '19 at 16:51
  • 1
    Why are you converting the file blob to a dataURL? And then putting it on a `` element? It would be far more efficient to upload the file blob directly. – georgeawg Apr 25 '19 at 18:23
  • @georgeawg I'm fairly new to JS, html5, etc. I've inherited this code and no one from the team who wrote it is around anymore, so I can't tell why it's done like this. But I've found [this question](https://stackoverflow.com/q/37832145/385646), which uses the same code, pretty much verbatim. So I'm guessing it came from some tutorial, course, or something similar. – MikMik Apr 26 '19 at 07:43
  • @georgeawg I've tried directly uploading the blob as read from the FileReader and it works fine! Thanks! – MikMik Apr 29 '19 at 07:46

0 Answers0