SpringBoot使用@ResponseBody返回图片的实现

网友投稿 1558 2023-03-15

SpringBoot使用@ResponseBody返回图片的实现

SpringBoot使用@ResponseBody返回图片的实现

以前使用HttpServletResponse可以通过输出流的方式来向前台输出图片。现在大部分都是使用springboot,在使用springboot之后,我们应该如何来修改代码呢?

Spring Boot项目搭建配置略过,可直接从官网简历一个demo

首先写一个Controller类,包括一个方法,如下:

package com.example.demo.common;

import org.springframework.http.MediaType;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import org.shttp://pringframework.web.bind.annotation.RestController;

import java.io.File;

import java.io.FileInputStream;

@RestController

@RequestMapping(value="/api/v1")

public class ImageTest {

@GetMapping(value = "/image",produces = MediaType.IMAGE_JPEG_VALUE)

@ResponseBody

public byte[] test() throws Exception {

File file = new http://File("E:\\ce\\1.jpg");

FileInputStream inputStream = new FileInputStream(file);

byte[] bytes = new byte[inputStream.available()];

inputStream.read(bytes, 0, inputStream.available());

return bytes;

}

}

我们首先在@GetMapping上加入produces告诉Spring,我们要返回的MediaType是一个图片(ihttp://mage/jpeg),然后加上@ResponseBody注解,方法返回byte[],然后将图片读进byte[],不加produces会报错。

浏览器访问接口测试一下,返回如下:

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:小程序开发平台(小程序开发)
下一篇:小程序中数量加减插件(微信小程序数学计算插件)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~