我正在實施Restful Web Service on Java,沒有框架。我的想法是從文件服務器發送圖像,因爲將它們存儲在數據庫中會降低服務器的速度。目前,我有以下代碼,它返回json的內容:java - 如何從RESTful web服務發送圖像?
@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;
}
}
想法?提前致謝。
這是問題所在。發送字節數組會降低服務器速度。這與將圖像存儲在數據庫中並通過字節數組發送到客戶端相同。沒有其他方式發送文件本身? –
您可以嘗試流式傳輸圖像。它可能會好一點。 'return Response.ok(new ByteArrayInputStream(bytes))。build();' – VHS
不會返回Response.ok(new FileInputStream(new File(「file.png」)))'better(and faster)因爲它不需要首先在內存中緩存整個文件內容,但是允許直接傳輸文件? – haraldK