繁体   English   中英

java - 如何从 RESTful Web 服务发送图像?

[英]java - how to send images from a RESTful web service?

我在Java上实现了一个Restful Web 服务,没有框架。 我的想法是从文件服务器发送图像,因为将它们存储在数据库中会降低服务器的速度。 目前,我有以下代码,它返回 json 内容:

@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;
    }
}

想法? 提前致谢。

尝试以下操作:

  @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();

但是,无论您选择哪个选项,它都会有点慢。 您可以将重定向链接发送到另一台服务器,该服务器可以独立于您的应用程序服务器将图像传送到客户端。 这比发送图像本身作为响应要好。

有一种解决方法,但这取决于您用于存储图像的文件服务器。

如果它是 Windows 文件服务器或 S3,您可以从 REST 服务返回图像的链接。 在 html 页面中,您可以使用<img src='${path_returned_from_rest_service}'> 但是(对于 Windows 文件服务器)这在 DMZ 中工作,而不是在客户端的外部 n/w 中工作。

如果应用程序要暴露给外部世界(在 DMZ 之外),那么您的 REST 服务应该输出字节数组。 顺便说一句,这不应该大大降低您的服务器的速度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM