美文网首页
springboot ResponseBodyAdvice 下载

springboot ResponseBodyAdvice 下载

作者: NazgulSun | 来源:发表于2021-09-15 15:18 被阅读0次

很多项目都是使用ResponseBodyAdvice 来封装统一的reponse接口,
或者进行加密等;
在下载文件的时候,由于返回的是inputstream,类似下面这种封装成Result 的结果是有问题的。
if(mediaType.includes(MediaType.APPLICATION_OCTET_STREAM)){
return body;
}
需要判断 mediaType,然后直接返回;

public class GlobalResponseBodyAdvice implements ResponseBodyAdvice {
    private static final Logger log = LoggerFactory.getLogger(GlobalResponseBodyAdvice.class);

    public GlobalResponseBodyAdvice() {
    }

    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(mediaType.includes(MediaType.APPLICATION_OCTET_STREAM)){
            return body;
        }
        HttpHeaders headers = serverHttpResponse.getHeaders();
        String requestId = UUID.randomUUID().toString();
        if (body instanceof Result) {
            ((Result)body).setRequestId(requestId);
            return body;
        } else {
            Result result = new Result(body);
            result.setRequestId(requestId);
            if (body instanceof String) {
                serverHttpResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                return JsonUtil.toFastJson(result);
            } else {
                return result;
            }
        }
    }
}

相关文章

网友评论

      本文标题:springboot ResponseBodyAdvice 下载

      本文链接:https://www.haomeiwen.com/subject/puokgltx.html