在Spring Cloud封裝的Feign中并不直接支持傳文件旬薯,但可以通過引入Feign的擴(kuò)展包來實(shí)現(xiàn)晰骑,本來就來具體說說如何實(shí)現(xiàn)。
原文:http://blog.didispace.com/spring-cloud-starter-dalston-2-4/
服務(wù)提供方(接收文件)
服務(wù)提供方的實(shí)現(xiàn)比較簡單绊序,就按Spring MVC的正常實(shí)現(xiàn)方式即可硕舆,比如:
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
@RestController
public class UploadController {
@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) {
return file.getName();
}
}
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
服務(wù)消費(fèi)方(發(fā)送文件)
在服務(wù)消費(fèi)方由于會使用Feign客戶端秽荞,所以在這里需要在引入feign對表單提交的依賴,具體如下:
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
定義文件上傳方的應(yīng)用主類和FeignClient岗宣,假設(shè)服務(wù)提供方的服務(wù)名為eureka-feign-upload-server
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
@FeignClient(value = "upload-server", configuration = UploadService.MultipartSupportConfig.class)
public interface UploadService {
@PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String handleFileUpload(@RequestPart(value = "file") MultipartFile file);
@Configuration
class MultipartSupportConfig {
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder();
}
}
}
在啟動了服務(wù)提供方之后蚂会,嘗試在服務(wù)消費(fèi)方編寫測試用例來通過上面定義的Feign客戶端來傳文件,比如:
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UploadTester {
@Autowired
private UploadService uploadService;
@Test
@SneakyThrows
public void testHandleFileUpload() {
File 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 (Exception e) {
throw new IllegalArgumentException("Invalid file: " + e, e);
}
MultipartFile multi = new CommonsMultipartFile(fileItem);
log.info(uploadService.handleFileUpload(multi));
}
}
完整示例:
讀者可以根據(jù)喜好選擇下面的兩個倉庫中查看eureka-feign-upload-server
和eureka-feign-upload-client
兩個項(xiàng)目:
- Github:https://github.com/dyc87112/SpringCloud-Learning/
- Gitee:https://gitee.com/didispace/SpringCloud-Learning/
如果您對這些感興趣耗式,歡迎star胁住、follow、收藏刊咳、轉(zhuǎn)發(fā)給予支持彪见!