openfeign如何声明下载文件的客户端

我有一个API服务,这个服务提供返回一个文件流的功能,接口如下:

/**
 * 下载文件
 * type
 * 0 原文
 * 1 译文
 * 2 双语
 * 3 解析
 * @param type
 * @param fileUuid
 * @return
 */
@RequestMapping(value = "/downloadFile", method = {RequestMethod.POST, RequestMethod.GET})
public ResponseEntity<FileSystemResource> downloadFile(
										@NotNull(message = "请选择文件类型") Integer type,
										@NotNull(message = "fileUuid不允许为空") String fileUuid) {
}

这个接口正常会返回一个文件,但是如果文件不存在,则会返回一个json串,提示文件不存在,那么这个是如何实现的呢?有两种方式:

  1. 抛出指定异常,使用异常拦截器统一处理

  2. 返回一个null类型的ResponseEntity<FileSystemResource>,同时接收HttpServletResponse response,将错误信息写入到response,如下:

    @RequestMapping(value = "/downloadFile", method = {RequestMethod.POST, RequestMethod.GET})
    public ResponseEntity<FileSystemResource> downloadFile(@NotNull(message = "请选择文件类型") Integer type,
                                                           @NotNull(message = "fileUuid不允许为空") String fileUuid,
                                                           HttpServletResponse response
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.getWriter().write("{code:500,msg:\"文件不存在1\",data:null}");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return new ResponseEntity<>(null, null, HttpStatus.OK);
        return null;
    }
    

如果上述接口只对内使用,需要声明式的客户端,应该如何做呢?只需要接收一个 ResponseEntity<Resource>即可:

@FeignClient(name = "edniutrans-document-api", url = "${edniutrans.document.api-url}")
public interface DocumentApiFeignService {


    /**
     * 下载文件
     * type
     * 0 原文
     * 1 译文
     * 2 双语
     * 3 解析
     */
    @RequestMapping(value = "/documentTrans/downloadFile", method = {RequestMethod.POST})
    ResponseEntity<Resource> downloadFile(
            @RequestParam(value = "type") Integer type,
            @RequestParam(value = "fileUuid") String fileUuid
    );
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

L-960

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值