AngularJS image upload preview without directive

12,029

Solution 1

I read this article, which helped me to solve the problem about uploading the image.

If you want to show your selected file, try this:

<img data-ng-src="data:image/png;base64,{{news.Photo}}" id="photo-id"/>

Explanation:

Your property for image in Model/ViewModel/Class must be an array of bytes, like

public byte[] Photo { get; set; }

The data:image/jpeg;base64 defines the byte array from news.Photo so it can be rendered correctly on the clients browser.

The $scope.news.Photo in your case is just an scoped variable which contains the drawed image with byte created by the byte equivalent in the $scope.uploadFile function from article.

I hope it will be also helpful for you.

Solution 2

Can you try this in your controller to pass your file object here:

$scope.fileReaderSupported = window.FileReader != null;
$scope.photoChanged = function(files){
    if (files != null) {
        var file = files[0];
    if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
        $timeout(function() {
            var fileReader = new FileReader();
            fileReader.readAsDataURL(file);
            fileReader.onload = function(e) {
                $timeout(function(){
                    $scope.thumbnail.dataUrl = e.target.result;
                });
            }
        });
    }
}
};

and on the view

<img ng-show="thumbnail.dataUrl != null" ng-src="{{ thumbnail.dataUrl }}" class="thumb">

demo here

Hope this help

Share:
12,029
brabertaser19
Author by

brabertaser19

Updated on June 14, 2022

Comments

  • brabertaser19
    brabertaser19 almost 2 years

    I'm uploading files via service:

    var addFile = function(files) {
      var deferred = $q.defer();
      var fd = new FormData();
      fd.append("file", files[0]);
      $http.post("/files", fd, {
          ***
        })
        .success(function(data, status, headers, config) {
          ***
        })
        .error(function(err, status) {
          ***
        });
        ***
    };
    

    and in controller I have something like:

    uplService.addFile($scope.files).then(function(url) {
      $scope.news.Photo = url;
    });
    

    and in HTML view:

    <input type="file" name="file" onchange="angular.element(this).scope().photoChanged(this.files)" />
    

    before that I uploaded file on-the-go, when I select file it goes directly to server, but now I need to display it in my form when I select it, but upload later, all I see in web is using directives, but how could I organize it without using directives?

  • brabertaser19
    brabertaser19 over 9 years
    {{news.Photo}} - but what to put there? files[0] or what? thank you
  • brabertaser19
    brabertaser19 over 9 years
    note, image is located in browser, not on server until i click 'save'
  • arman1991
    arman1991 over 9 years
    I know that it must be shown before 'save', I updated my answer.