1

This may come off as a bit newb-ish, but I don't really know how to approach this.

Can anyone recommend me a way of delivering and image from a flask backend, after being called by an angular $http.get call?

Brief example of what I am trying to do.

//javascript code
myApp.controller('MyCtrl', function($scope, $http){
    $http.get('/get_image/').success(function(data){
        $scope.image = data;
    });
});

#flask back end
@app.route('/get_image/', methods= ['GET', 'POST'])
def serve_image():
    image_binary = get_image_binary()   #returns a .png in raw bytes
    return image_binary

<!-- html -->
<html ng-app= "myApp">
    <div ng-controller= "MyCtrl">
        {{ image }}
    </div>
</html>

So as you can see, I am attempting to serve a raw-byte .png image from the flask backend, to the frontend.

I've tried something like this

<html>
    <img src= "/get_image/">
</html>

But the trouble is, 'get_image_binary' takes a while to run, and the page loads before the image is ready to be served. I want the image to load asyncronously to the page, only when it is ready.

Again, I am sure there are many ways to do this, probably something built into angular itself, but it is sort of difficult to phrase this into a google-able search.

Zack
  • 13,454
  • 24
  • 75
  • 113

1 Answers1

3

Can't speak to the flask stuff, but below is some AngularJS code.

This directive won't replace the source attribute until after Angular manipulates the DOM and the browser renders (AngularJS : $evalAsync vs $timeout).

HTML:

<div ng-controller="MyController">
   <img lazy-load ll-src="http://i.imgur.com/WwPPm0p.jpg" />
</div>

JS:

angular.module('myApp', [])
.controller('MyController', function($scope) {})
.directive('lazyLoad', function($timeout) {
    return {
        restrict:'A',
        scope: {},
        link: function(scope, elem, attrs) {
            $timeout(function(){ elem.attr('src', attrs.llSrc) });
        },
    }
});

Same code in a working JSFiddle

Community
  • 1
  • 1
Marc Kline
  • 9,399
  • 1
  • 33
  • 36
  • I am a bit confused as to how this works. I've not yet tried the route that will generate my image, but am using the imgur test image that you provided. Before adding the controller code I was able to see the image of the dog. Now I just see the default, "missing image" icon. Does this code show the picture of the dog for you? – Zack Apr 24 '14 at 15:17
  • Damn, nevermind, I see the dog now. Cache issue I think. Now I'm trying to get it to load my image from the backend, it was working before when I did a page reload (again, I suspect a cache issue), but I get the missing image icon when trying to use my own png file. – Zack Apr 24 '14 at 15:21
  • This worked, thank you! (My image was taking a long time to be created, but that is another problem) – Zack Apr 24 '14 at 19:38
  • How do you combine this directive with the `$http.get('/get_image/')` ? – Wim Deblauwe Dec 16 '15 at 15:57