使用Feign调用文件上传

本文介绍如何使用Feign实现文件上传功能,包括依赖配置、FeignClient接口定义及Controller实现等关键技术点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Feign调用文件上传

目前feign不支持调用文件上传接口需要自行配置来满足feign的调用方式

maven代码块

12345678910  <dependency>    
    <groupId>io.github.openfeign.form</groupId>    
    <artifactId>feign-form-spring</artifactId>    
    <version>3.2.2</version>    
  </dependency>    
  <dependency>    
      <groupId>io.github.openfeign.form</groupId>    
      <artifactId>feign-form</artifactId>    
      <version>3.2.2</version>    
  </dependency>  

FeignClient接口代码块

1234567891011121314151617181920  @FeignClient(url = "${manager.base-gateway}"+"/base-file-mgt", name = "base-file-mgt",configuration = UploadFileService.FeignMultipartSupportConfig.class)
  public interface UploadFileService {
  
    @RequestMapping(method = RequestMethod.POST, value = "/api/upload-file",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    FileInfoDTO uploadPayImage(@RequestPart(value = "file") MultipartFile file);
    
      class FeignMultipartSupportConfig {
    
          @Bean
          public Encoder multipartFormEncoder() {
              return new SpringFormEncoder();
          }
    
          @Bean
          public feign.Logger.Level multipartLoggerLevel() {
              return feign.Logger.Level.FULL;
          }
      }
  }
  • feign.Logger.Level.FULL 日志打印类型
  • SpringFormEncoder 字符集转换
打开注解@RequestPart代码
12345678910111213141516171819202122232425262728  @Target(ElementType.PARAMETER)
  @Retention(RetentionPolicy.RUNTIME)
  @Documented
  public @interface RequestPart {

    /**
     * Alias for {@link #name}.
     */
    @AliasFor("name")
    String value() default "";
  
    /**
     * The name of the part in the {@code "multipart/form-data"} request to bind to.
     * @since 4.2
     */
    @AliasFor("value")
    String name() default "";
  
    /**
     * Whether the part is required.
     * <p>Defaults to {@code true}, leading to an exception being thrown
     * if the part is missing in the request. Switch this to
     * {@code false} if you prefer a {@code null} value if the part is
     * not present in the request.
     */
    boolean required() default true;

  }

@RequestPart 才是支持文件上传的注解。{@code “multipart/form-data”}

FileInfoDTO.java

1234567891011121314151617181920212223242526  public class FileInfoDTO implements Serializable {

    private Long id;

    private String tenantId;

    private String createUserId;

    private String filePath;

    private String fileId;

    private ZonedDateTime createDate;

    private Integer disabled;

    private String cosPath;

    private String fileName;

    private ZonedDateTime updateDate;

    private String updateUserId;
    
    //get and set 
    }

###Controller代码块

12345678910  @PostMapping("/orders-pay-img")
    @Timed
    @ApiOperation(value = "上传订单图片", httpMethod = "POST", notes = "上传订单图片")
    public ResponseEntity<FileInfoDTO> createOrder(@RequestParam(value = "file") MultipartFile file,
                                         @ApiParam(name = "filePath", value = "指定文件存储路径(不指定则自动生成文件路径)") @RequestParam(value = "filePath", required = false) String filePath) {

        log.debug("REST request to iamge file : {}", file);
        FileInfoDTO responseEntity= uploadFileService.uploadPayImage(file,tenantId,createUserId,filePath);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(responseEntity));
    }
### 使用 Feign 实现文件上传数组接口的调用 为了实现使用 Feign 调用文件上传数组接口的功能,可以按照以下方式构建应用程序: #### 1. 配置 Spring Boot 应用程序以支持 Feign 客户端 确保在启动类上添加 `@SpringBootApplication` `@EnableFeignClients` 注解来启用 Feign 功能并指定要扫描的包路径[^3]。 ```java @SpringBootApplication @EnableFeignClients("com.example.feignclients") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` #### 2. 创建 Feign 接口定义 定义一个带有适当 HTTP 方法签名的 Feign 接口用于处理多部分表单数据提交。这里假设目标服务提供了一个接收文件列表作为输入参数的 API 端点 `/upload/files`[^1]。 ```java import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; @FeignClient(name = "file-upload-service", url = "${service.url}") public interface FileUploadService { @PostMapping(value = "/upload/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) String uploadFiles(@RequestPart("files") List<MultipartFile> files); } ``` #### 3. 在消费者应用中注入并使用 Feign Client 通过依赖注入获取上述定义好的 Feign 客户端实例,在业务逻辑层调用其提供的方法完成实际操作[^2]。 ```java @Service public class UploadServiceImpl implements UploadService { private final FileUploadService fileUploadService; @Autowired public UploadServiceImpl(FileUploadService fileUploadService) { this.fileUploadService = fileUploadService; } @Override public ResponseEntity<String> handleFileUpload(List<MultipartFile> multipartFiles) throws IOException { try { // Call the remote service via Feign client to perform batch uploads. String result = fileUploadService.uploadFiles(multipartFiles); return new ResponseEntity<>(result, HttpStatus.OK); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } ``` 以上就是利用 Feign 来实现批量文件上传的一个简单例子。需要注意的是,具体实现细节可能会因项目环境不同而有所差异,比如使用的序列化器/反序列化器库版本、网络配置等都可能影响最终效果。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值