方式一:直接针对响应对象(response)实现
@RestController
@Slf4j
@Api(tags = SwaggerConfig.TAG_IMAGE)
@RequestMapping(SwaggerConfig.TAG_IMAGE)
public class ImageController {
@GetMapping(value = "/getImage")
@ApiOperation("获取图片-以ImageIO流形式写回")
public void getImage(HttpServletResponse response) throws IOException {
OutputStream os = null;
try {
// 读取图片
BufferedImage image = ImageIO.read(new FileInputStream(new File("F:\\谷歌下载\\未命名文件.png")));
response.setContentType("image/png");
os = response.getOutputStream();
if (image != null) {
ImageIO.write(image, "png", os);
}
} catch (IOException e) {
log.error("获取图片异常{}",e.getMessage());
} finally {
if (os != null) {
os.flush();
os.close();
}
}
}
}
方式二:使用springmvc框架的ResponseEntity对象封装返回数据,设置HttpHeader中的content-type,如:image/png
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getFile(@RequestParam long id) {
Result result = fileService.getFile(id);
if (result.getCode() == 1) {
MediaType mediaType = MediaType.parseMediaType(result.getMsg());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
ResponseEntity e = new ResponseEntity(result.getData(), headers, HttpStatus.OK);
return e;
}
return ResponseEntity.status(404).body(result.getMsg());
}
方式三:在@RequestMapping中加上 produces 来设置图片类型, 不需要单独设置HttpHeaders
支持数组,如:produces = {MediaType.IMAGE_JPEG_VALUE,MediaType.IMAGE_PNG_VALUE}
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.springframework.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 File("E:\\ce\\1.jpg");
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes, 0, inputStream.available());
return bytes;
}
}
附项
-
writeWithMessageConverters ==> 将处理响应的结果,写入响应中
-
通过 HttpServletResponse 得到的 PrintWriter 和 ServletOutputStream 不需要手动关闭。在 servlet 完成生命周期之后,servlet 容器会自动关闭流。
-
// 将通过converter将内容body写入outputMessage ((HttpMessageConverter) converter).write(body, selectedMediaType, outputMessage)