2017-01-28 49 views
0

我正在實施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; 
    } 
} 

想法?提前致謝。

回答

0

嘗試以下操作:

@GET 
    @Produces(Metodos.Parametros.TYPE_IMAGE_PNG) 
    public Response getImage() { 
     byte[] bytes = Files.toByteArray("file.png"); 
     return Response.ok(bytes).build(); 
    } 

您可以嘗試流中的圖像。它可能會好一點。 return Response.ok(new ByteArrayInputStream(bytes)).build();

但無論您選擇哪個選項,它都會有點慢。您可以將重定向鏈接發送到另一臺服務器,該服務器可以獨立於應用服務器將圖像傳送到客戶端。它比發送圖像本身作爲迴應要好。

+0

這是問題所在。發送字節數組會降低服務器速度。這與將圖像存儲在數據庫中並通過字節數組發送到客戶端相同。沒有其他方式發送文件本身? –

+0

您可以嘗試流式傳輸圖像。它可能會好一點。 'return Response.ok(new ByteArrayInputStream(bytes))。build();' – VHS

+0

不會返回Response.ok(new FileInputStream(new File(「file.png」)))'better(and faster)因爲它不需要首先在內存中緩存整個文件內容,但是允許直接傳輸文件? – haraldK

0

有一個解決辦法,但它取決於您用於存儲圖像的文件服務器。

如果是Windows文件服務器或S3,則可以從REST服務返回圖像的鏈接。在html頁面中,您可以使用<img src='${path_returned_from_rest_service}'>。但是(對於Windows文件服務器),這在DMZ內工作,而不是在客戶端的外部n/w。

如果應用程序要暴露於外部世界(DMZ之外),那麼您的REST服務應該吐出字節數組。 順便說一句,這不應該大大減慢你的服務器。