0

I want to serve images using ExpressJS in a private manner. I figured that this is not possible by serving them statically. Therefore, I serve them upon requests that have valid permissions (see 'validateTokens(req)' call below). However, when receiving them in my AngularJS app I am not able to display in the DOM.

Here is my server's relevant code:

expressServer.get('/image', function (req, res){
    if (validateTokens(req)) {
        var filePath = path.join(__dirname, "./testImage.jpg");
        res.sendFile(filePath);
    }
});

Here is my client's relevant code:

var app = angular.module("app", []);
app.controller("indexController", function($http, $scope, $window){
    $http({
        method: 'GET',
        url: '/image'
    }).then(function successCallback(response) {
        var blob = new Blob([response.data], {type : 'image/jpeg'});
        $scope.imageData = $window.URL.createObjectURL(blob);
    }, function errorCallback(response) {
    });
});

Here is my DOM's template:

<!DOCTYPE html>
<html ng-app="app">
    <head>
        <meta charset="utf-8">
        <title>Node Testing</title>
        <script src="angular.min.js"></script>
        <script src="app.js"></script>
    </head>
    <body ng-controller="indexController as indexCtrl">
        <img data-ng-src="{{imageData}}" alt="Image to be shown" />
    </body>
</html>
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
Jonathan Ginsburg
  • 1,008
  • 1
  • 8
  • 15

1 Answers1

0

The method you are using now for sending the image sendFile is intended for downloading purposes.

It sets all the necessary headers to force the browser to start a download.

API Reference for sendFile

What you can do is after validation send a base64 encoded image which can be set as an image's src property

var fs = require("fs");
fs.readFile("testimage.jpg", function(err, buffer){
    var base64Image = new Buffer(buffer, 'binary').toString('base64');
    res.send('data:image/jpeg;base64,' + base64Image);
});

Then from your angular js code

$http({
    method: 'GET',
    url: '/image'
}).then(function successCallback(response) {
    $scope.imageData = response.data;
}, function errorCallback(response) {
});
eltonkamami
  • 5,134
  • 1
  • 22
  • 30