1

I am hosting a website on Heroku with Node.js and AngularJs but my database is somewhere else (say abc.com).

I want to store image in mysql database at abc.com (Not saving images on heroku).

I have used text, blob, longblob datatype to store image from AngularJs using ng-file-upload (npm module). When i upload image, it is stored in database.

I have created a rest api on abc.com to fetch database values and consuming rest in node.js.

Now, I want to fetch image from database and display in html page. I have fetched database value from mysql -> abc.com -> node.js -> angularjs and tried angular-base64, atob and btoa to convert database value to show image, but i had no luck.

let _arrayBufferToBase64 = function (buffer) {
    return $base64.encode(buffer);
};

let _arrayBufferToBase64 = function (buffer) {
    console.log('_arrayBufferToBase64')
    var binary = '';

    var bytes = new Uint8Array(new Buffer(buffer, 'base64'));
    // var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;
    console.log(len);
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
};

UtilService.fetchImage()
    .then(function(res){
        console.log(res);
        if(res.success){
            let data = res.data[0].profile_pic;
            console.log(data);
            $scope.img = 'data:image/png;base64,'+_arrayBufferToBase64(data);
            // $scope.img = 'data:image/png;base64,'+data;
            console.log($scope.img);
        } else {
            console.log('image not found');
            $scope.alt = "Image is not found";
        }
    })
}
template: '<img class="img-responsive img-hover" ng-src={{img}} alt={{alt}}"/>'

When my database was in heroku, above code was working fine. But now i need some help.

Thanks in advance...

Arun Kumar
  • 323
  • 1
  • 4
  • 15

1 Answers1

0

Found solution for my question and want to share with others.

My requirement was to send image from angularjs to nodejs, and from nodejs to abc.com (where my database is present).

From angularjs, I used ng-file-upload as:

<div class="col-sm-12">
    <button class="col button btn btn-primary btn-sm" ng-model="$ctrl.imageFile" id="imageFile" name="imageFile" ngf-pattern="'image/*'" ngf-select ngf-accept="'image/*'" ngf-max-size="2MB" ngf-resize="{width: 512, height: 512, quality: 1}">Select/Change</button>
    <p class="text-danger text-center" ng-show="profileImageForm.imageFile.$error.maxSize">
        2MB is max size
    </p>
    <p class="text-danger text-center" ng-show="profileImageForm.imageFile.$error.pattern">
        Select image
    </p>
    <button ng-show="!!$ctrl.imageFile" class="col btn btn-primary btn-sm" ng-click="$ctrl.uploadProfilePic($ctrl.imageFile)">Upload</button>
</div>


Upload.upload({
    // request method is post
    url: 'server-url',
    data: { imageFile: $ctrl.imageFile },
    headers: Utility.authHeader
}).then(function (resp) {
    // ...
})

On server side (NodeJs):

app.post('server-url', , function (req, res) {
    const formidable = require('formidable');
    const form = new formidable.IncomingForm();
    const base64Img = require('base64-img');

    form.encoding = 'utf-8';
    form.parse(req, function (err, fields, file) {
        logger.debug(file);
        if (!!file.imageFile && !!file.imageFile.path) {
            const uploadedImagePath = file.imageFile.path      // imageFile is form param name
            logger.debug(uploadedImagePath);        // image will be stored in temp folder on server

            // convert image to base64 encoded string
            base64Img.base64(uploadedImagePath, function (err, base64String) {
                logger.debug(base64String);
                // send base64String to abc.com and store in database
            });
        } else {
            logger.debug("Image path is not available");
            res.json({ success: false })
        }
    });
})

When i want to display stored image: Fetch base64String from database and use as if it is image:

Utility.fetchImage()
    .then(function(res){
        $ctrl.img = res.data;
    })

<img class="img-responsive img-hover" ng-src={{img}} />

I hope it will help you. I would be happy to know other alternatives as well.

Arun Kumar
  • 323
  • 1
  • 4
  • 15