文件發送方
1.OpenFeign默認不支持文件上傳,需要通過引入Feign的擴展包來實現,添加依賴
文件上傳方需要添加如下依賴:
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
</dependencies>
並且添加如下配置類:(實測不需要添加這個配置類也行,源碼可見SpringEncoder、SpringFormEncoder、FeignClientsConfiguration)
@Configuration
public class FeignConfiguration {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Encoder feignEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
person類:
@Data
public class Person {
private String name;
private Integer age;
}
測試頁面:index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/hello/test" method="post" enctype="multipart/form-data">
<input type="text" name="name">
<input type="text" name="age">
<input type="file" name="file">
<br>
<div>上傳文件:<input type="file" name="file2" multiple="multiple"></div>
<input type="submit" value="Submit">
</form>
</body>
</html>
controller:
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private Client2FeignService client2FeignService;
@PostMapping("/test")
public String test(@RequestParam(value = "file")MultipartFile file, @RequestParam(value = "file2")MultipartFile[] files,Person person) {
return client2FeignService.test(file, files, person.getAge(), person.getName());
}
}
Client2FeignService接口:
注意:
PostMapping
注解的consumes
要設置成MediaType.MULTIPART_FORM_DATA_VALUE
,不然會直接報錯MultipartFile
類型前面用@RequestPart
注解修飾,不然文件會傳輸不過去
@FeignClient("client2")
public interface Client2FeignService {
@PostMapping(value = "/hello/test",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String test(@RequestPart(value = "file") MultipartFile file, @RequestPart(value = "file2")MultipartFile[] files,
@RequestParam("age") Integer age, @RequestParam("name") String name);
}
文件接收方
controller:
@RestController
@RequestMapping("/hello")
public class HelloController {
@PostMapping("/test")
String test(@RequestPart(value = "file") MultipartFile file, @RequestPart(value = "file2")MultipartFile[] files,
@RequestParam("age") Integer age, @RequestParam("name") String name) {
System.out.println(age);
System.out.println(name);
System.out.println(file.getSize());
for (MultipartFile multipartFile : files) {
System.out.println(multipartFile.getSize());
}
return "ok";
}
}
測試
我這里:file參數只有一個文件,file2參數我上傳了兩個文件
查看文件接收方的輸出:
單文件、多文件和其他普通參數都可以發送。
那這里name
和age
為什么要拆開來傳輸,而不直接傳輸Person
實體類呢?
因為使用Person
會直接報錯,我目前沒有找到好的辦法。
那有人會問,如果實體類有很多字段怎么辦,一個一個拿出來作為方法參數傳過去嗎?
當然不用,直接文件發送方把實體類轉成json字符串,然后接收方再反序列化回來不就行了嗎。