Jersey——返回图片格式数据

    xiaoxiao2025-08-07  17

    一、背景 在使用Jersey实现Restful后端设计的时候,Jersey常用用于返回JSON格式数据,实际上Jersey是可以返回其他格式的数据的,在MVC中与Springmvc都是可以做为C的,由于项目上需要通过Jersey实现返回图片流的接口,为简单起见现采用springboot+jersey搭建示例环境。

    二、操作步骤

    使用Spring initializer创建,引入springboot和jersey,生成的配置文件如下: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jersey</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> 对于返回图片流有三种方式: a) 直接放回byte[]数组: @GET @Path("") @Consumes("image/*") @Produces("image/png") public Response getImage() { final File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\7a04373d04277b26de8e7397ea5a9d46.jpg"); try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); StreamUtils.copy(new FileInputStream(file), bos); return Response.ok(bos.toByteArray()).build(); } catch (IOException e) { e.printStackTrace(); } return null; }

    b) 直接返回BufferedImage对象

    @Path("2") @GET @Consumes("image/*") @Produces("image/*") public Response getImage2() { final File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\7a04373d04277b26de8e7397ea5a9d46.jpg"); try { BufferedImage bufferedImage = ImageIO.read(file); return Response.ok(bufferedImage, "image/png").build(); } catch (IOException e) { e.printStackTrace(); } return null; }

    c) 直接返回InputStream对象

    @GET @Path("3") @Consumes("image/*") @Produces("image/png") public Response getImage4() { final File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\7a04373d04277b26de8e7397ea5a9d46.jpg"); try { return Response.ok(new FileInputStream(file)).build(); } catch (IOException e) { e.printStackTrace(); } return null; }

    三、参考链接

    Spring Boot Jersey ExampleHow to return a PNG image from Jersey REST service method to the browser
    最新回复(0)