当前位置:数据分析 > Spring Cloud Feign的文件上传实现

Spring Cloud Feign的文件上传实现

  • 发布:2023-10-10 22:52

Spring Cloud封装的Feign并不直接支持文件上传,但是可以通过引入Feign的扩展包来实现。下面我们来具体讲一下如何实现。

服务提供商(接收文件)

服务提供者的实现比较简单,按照Spring MVC的正常实现即可,如:

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
公共类应用程序{

@RestController
公共类UploadController {

@PostMapping(value = "/up") loadFile", 消耗 = MediaType .MULTIPART_FORM_DATA_VALUE)
public String handleFileUpload(@RequestPart(value = "file") MultipartFile 文件) {
return file.getName();
}

}

public static void main(String [] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}

}

服务消费者(发送文件)

由于服务消费者端会使用Feign客户端,所以这里需要介绍一下Feign对表单提交的依赖,如下:


io.github.openfeign.form
feign-form
3.0.3


io.github.openfeign。形式
feign-form-spring
3.0.3


commons-fileupload
commons-fileupload
1.3.3

定义文件上传器的应用主类和FeignClient,假设服务提供者的服务名为eureka-feign-upload-server

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
公共类应用程序{

公共静态无效main(String [] args){
新SpringApplicationBuilder(Application.class).web(true ).run(args);
}

}

@FeignClient(value = "上传服务器", 配置 = UploadService.MultipartSupportConfig.class)
公共接口UploadService {

@PostMapping(value = "/uploadFile", 消耗 = MediaType.MULTIPART_FORM_DATA_VALUE)
String handleFileUpload(@RequestPart(value = "file") MultipartFile file);

@Configuration
class MultipartSupportConfig {
@Bean
            public Encoder feignFormEncoder( ) {
                      返回新的SpringFormEncoder();

启动服务提供者后,尝试在服务消费者上编写一个测试用例,通过上面定义的Feign客户端传输文件,如:

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
公共类UploadTester {

@Autowired
私有UploadService uploadService;

@Test
@SneakyThrows
public void testHandleFileUpload() {

文件 file = new File("upload.txt");
       DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
               MediaType.TEXT_PLAIN_VALUE, true, file.getName());

       try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
           IOUtils.copy(input, os);
       } catch (异常 e) {
           扔新的IllegalArgumentException("无效文件:" + e, e);
       }

       MultipartFile multi = new CommonsMultipartFile(fileItem);

       www.sychzs.cn(uploadService.handleFileUpload(multi));
   }

}    


相关文章