如何在Restful Jax-rs中发送图像

Sur*_*rya 3 jax-rs

我想从java服务器(Restful Jax-rs)发送一个图像.我的客户端是Android.

@GET
public Response getUserImage() {
byte[] image =new byte[1024];
return Response.ok(image, MediaType.APPLICATION_OCTET_STREAM).header("content-attachment; filename=image_from_server.png") .build();
Run Code Online (Sandbox Code Playgroud)

但这里有一个下载框即将推出.所以我想下载没有下载框,当我在浏览器上运行请求URL时,它应该自动打开.谢谢.

Jin*_*won 9

我相信那是因为你指定的application/octet-stream.

我认为你应该使用image/jpegimage/png.

@GET
@Produces({"image/png"})
public Response getUserImage() {

    final byte[] image = ...;
    // say your image is png?

    return Response.ok().entity(new StreamingOutput(){
        @Override
        public void write(OutputStream output)
           throws IOException, WebApplicationException {
           output.write(image);
           output.flush();
        }
    }).build();
}
Run Code Online (Sandbox Code Playgroud)