I'm implementing a Restful Web Service on Java, with no framework. My idea is to send images from a file server, because storing them on a database slows the server down. By the moment, I have the following code, which returns json content:
@Path("articulo")
public class ArticuloResource {
@Context
private UriInfo context;
private final ArticuloService service;
private final Gson gson;
/**
* Creates a new instance of ArticuloResource
*/
public ArticuloResource() {
this.service = new ArticuloService();
this.gson = new Gson();
}
/**
* Retrieves representation of an instance of ArticuloResource
* @return an instance of com.tienda.rest.pojo.Articulo
*/
@GET
@Produces(Metodos.Parametros.TYPE_APPLICATION_JSON)
public String getJson() {
return this.gson.toJson(this.service.seleccionarTodo());
}
@GET
@Path("novedades")
@Produces(Metodos.Parametros.TYPE_APPLICATION_JSON)
public String getNovedades() {
return "Novedades";
}
@GET
@Path("{id}")
@Produces(Metodos.Parametros.TYPE_APPLICATION_JSON)
public String getArticulo(@PathParam("id") Integer id) {
return this.gson.toJson(this.service.getUnique(id));
}
/**
* PUT method for updating or creating an instance of ArticuloResource
* @param content representation for the resource
* @return an HTTP response with content of the updated or created resource.
*/
@PUT
@Consumes(Metodos.Parametros.TYPE_APPLICATION_JSON)
public void putJson(Articulo content) {
}
@GET
@Produces(Metodos.Parametros.TYPE_IMAGE_PNG)
public Response getImage() {
return null;
}
}
Ideas? Thanks in advance.
Try following:
@GET
@Produces(Metodos.Parametros.TYPE_IMAGE_PNG)
public Response getImage() {
byte[] bytes = Files.toByteArray("file.png");
return Response.ok(bytes).build();
}
You can try to stream the image. It might be a bit better. return Response.ok(new ByteArrayInputStream(bytes)).build();
However no matter which option you choose, it's going to be a bit slow. You can send a redirect link to another server which can deliver the image to the client independently of your app server. It is better than sending the image itself in response.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments