CodeTrooper
CodeTrooper

Reputation: 1888

AngularJS image preview

I have the following input file:

<div class="col s12">
     <h6>Foto</h6>
     <div class="file-field input-field">
          <div class="btn pink darken-2 waves-effect waves-light">
               <span>Archivo</span>
               <input type="file" name="image" id="image"
               file-model="picture.image" custom-on-change="renderPreview">
           </div>
           <div class="file-path-wrapper">
               <input class="file-path" type="text" readonly>
           </div>
    </div>
</div>

When the directive custom-on-change triggers, I get the file from the input (console.log() works here) so what I want to do next is do a preview of the image I just selected:

$scope.renderPreview = function(event){
      var picture = event.target.files;
      console.log(picture);
      $('#image-preview').attr('src', picture);
}

Which is supposed to be placed here:

<h5 class="center-align">Vista Preliminar</h5>
<div class="col s6 offset-s3">
     <div class="image-preview-container">
          <img id="image-preview" class="z-depth-2">
     </div>
</div>

However, no image is rendered. I've been trying to look for a solution to this, and people always send you to those angular file upload plugins.. I do not want to use those plugins for just a simple task like this.

Is there a way I can render the picture so that the user can see it just before uploading it?

EDIT

My custom-on-change directive:

angular.module('sccateringApp')
  .directive('customOnChange', function () {
      return {
      restrict: 'A',
      link: function (scope, element, attrs) {
        var onChangeHandler = scope.$eval(attrs.customOnChange);
        element.bind('change', onChangeHandler);
      }
    };
  });

Upvotes: 2

Views: 3774

Answers (1)

Rohan Pawar
Rohan Pawar

Reputation: 2013

In your code var picture is array of files, so use index to show image

$scope.renderPreview = function(event){
      var pictures = event.target.files;
      $('#image-preview').attr('src', pictures[0]);
}

as per @Hanlet Escaño suggest try below code

$scope.renderPreview = function (event) {
  if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      $('#image-preview').attr('src', e.target.result);
    }

    reader.readAsDataURL(event.target.files[0]);
  }
};

Upvotes: 3

Related Questions