Arav KT Arav KT - 1 year ago 72
AngularJS Question

How to display images in web page using angularjs?

I already know how to save images in mongodb using angularjs and java to save it in my mongodb,

I need to get the saved image from mongodb and display it in an html page using AngularJS.

This is my controller for getting image

public Response getById(@PathParam("id") String id) throws IOException
Response response = null;
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB mongoDB = mongoClient.getDB("sampleDB");
DBCollection collection = mongoDB.getCollection("filestore");
BasicDBObject query = new BasicDBObject();
ObjectId oid = new ObjectId(id);
query.put("_id", oid);
GridFS fileStore = new GridFS(mongoDB, "filestore");
GridFSDBFile gridFile = fileStore.findOne(query);
InputStream in = gridFile.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int data =;
while (data >= 0)
out.write((char) data);
data =;
ResponseBuilder builder = Response.ok(out.toByteArray());
builder.header("Content-Disposition", "attachment; filename=");
response =;
return response;

This is my angularjs for getting image

var userImagePromise = $http.get("../api/s3/" + $scope.user.profileImage[0].id);
userImagePromise.success(function(data, status, headers, config) {
$scope.imageData = data;
userImagePromise.error(function(data, status, headers, config) {

This is my html for displaying image

<img id="userProfileImg" height="150px" width="150px" ng-src="data:image/png;base64,{{imageData}}">

if I simply put the link to browser i got this output in octect-stream

�PNG .....

How to display image in html?Any error in my code wise?

Image for getting output

Sam Sam
Answer Source

i think your base64 code is not converting images properly, so check my code it may help you.

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

BufferedImage buffimage = File(imagePath));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffimage, "png", baos);
String img = Base64.encode(baos.toByteArray());

send this img variable to your angularjs code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download