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

猜你喜欢

转载自blog.csdn.net/weixin_43702146/article/details/129295178