Asim Raja Asim Raja - 1 month ago 10
Node.js Question

Image as response and its details with nodejs

I want to send an image with my json data as a response from Server(nodejs) to client-side(angularjs). I have seen answers like sending image as json but sending data as session-cookie but they weren't satisfying enough.
What is the best way to send image? As the image in jpg or png format or sending its absolute path and the client downloads it?

Secondly I want to ask is there anyway I can embed the picture with my response and send it assuming there will be only one picture and space will not be an issue if so how can i do that?

Answer Source

Unfortunately I don't have the syntax for nodejs but believing the concept will remain same. Here is what I do :

define that the function GET is capable of producing "image/*" for example:

@GET
@Produces("image/*")
public Response getImage() {
   String image = "scroll0015.jpg";
   File f = new File(image);
   if (!f.exists()) {
       throw new WebApplicationException(404);
   }
   String mt = new MimetypesFileTypeMap().getContentType(f);
   return Response.ok(f, mt).build();
}

And then while you are constructing the response you tell in the response header what content of file you are sending .

1) If your user/client has the ability to access a shared location then it is a good to idea to point to the new URL . for example using amazon S3 .

2) does your image change quite often ? let the user cache it.

3) if your servers can take the load of sending the images well and good otherwise you use cloud service.