kg99
kg99

Reputation: 117

How to serve images to client nodejs and angular

I am trying to send .jog images to the client but I fail.

app.get('/image', function(req, res){;


res.sendfile(path.resolve(path.resolve(__dirname,'/Imagepath/image.jpg")));

});

on my angular side

  $http({
    method:'GET',
    url:'/image',
  }).then(function (response){
    $scope.image= response.data;


  })


<img id="imgid" ng-src="{{image}}" width="500" height="400"/>

The problem is that the response is some binary data. How can I get it to send me data that can be displayed on the img src. How can I show images in my server folder on the client side?Thank you.

Upvotes: 2

Views: 3556

Answers (2)

jmuise
jmuise

Reputation: 46

Unless you need to send the image as data (generated dynamically for example) you could just set the path to the image as your src.

Assuming you are using express.js you can then have it serve up your images as static content: http://expressjs.com/en/starter/static-files.html

app.use(express.static('public'));

and with an image stored at public/images/image.jpg your angular code could just load the image as:

$scope.image = "/images/image.jpg"

<img id="imgid" ng-src="{{image}}" width="500" height="400"/>

Upvotes: 1

gelliott181
gelliott181

Reputation: 1028

Understandably, <img> tags don't support sourcing from binary through attributes, so you'll have to look at another solution.

You could try converting the binary encoding to Base64 at the client side using TypedArrays together with the btoa function. Then you'd be able to use

<img ng-src="data:image/JPEG;base64,{{myImage}}">

Answer from How to return image from $http.get in AngularJS

So essentially you need to take response.data and convert to base64, then assign it to $scope.image. After that you can display it using the img tag referenced above.

Upvotes: 0

Related Questions