【常规做法】不提供Response给你,你有什么办法返回一张动态临时图片给用户呢?(SpringBoot项目)...

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

首先写一个 Controller 类,包括一个方法(看清楚哦!方法的返回类型是byte[]),如下:

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

关键在这里produces = MediaType.IMAGE_JPEG_VALUE

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

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

RequestMapping 注解说明

@Target({ElementType.METHOD, ElementType.TYPE})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
@Mapping  
public @interface RequestMapping {  
      String[] value() default {};  
      RequestMethod[] method() default {};  
      String[] params() default {};  
      String[] headers() default {};  
      String[] consumes() default {};  
      String[] produces() default {};  
}  

  • value: 指定请求的实际地址, 比如 /action/info 之类

  • method:指定请求的 method 类型, GET、POST、PUT、DELETE 等

  • consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

  • produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回

  • params:指定 request 中必须包含某些参数值是,才让该方法处理

  • headers:指定request中必须包含某些指定的header值,才能让该方法处理请求

再举个例子

@Controller    
@RequestMapping(value = "/users", method = RequestMethod.POST, consumes="application/json", produces="application/json")    
@ResponseBody  
public List<User> addUser(@RequestBody User userl) {        
    // implementation omitted    
    return List<User> users;  
}    

方法仅处理 request Content-Type 为 “application/json” 类型的请求.

produces 标识 ==>处理 request 请求中 Accept 头中包含了 "application/json" 的请求,
同时暗示了返回的内容类型为 application/json;


作者:二十-帅帅 和   胖鹅68

链接:

https://blog.csdn.net/qq_18298439/article/details/89315478

https://blog.csdn.net/hbiao68/article/details/87366694

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值