您好,登錄后才能下訂單哦!
在Spring Cloud封裝的Feign中并不直接支持傳文件,但可以通過(guò)引入Feign的擴(kuò)展包來(lái)實(shí)現(xiàn),本來(lái)就來(lái)具體說(shuō)說(shuō)如何實(shí)現(xiàn)。
服務(wù)提供方(接收文件)
服務(wù)提供方的實(shí)現(xiàn)比較簡(jiǎn)單,就按Spring MVC的正常實(shí)現(xiàn)方式即可,比如:
@RestController public class UploadController { @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) { return file.getName(); } }
服務(wù)消費(fèi)方(發(fā)送文件)
在服務(wù)消費(fèi)方由于會(huì)使用Feign客戶端,所以在這里需要在引入feign對(duì)表單提交的依賴,具體如下:
<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> </dependency>
定義FeignClient,假設(shè)服務(wù)提供方的服務(wù)名為 upload-server
@FeignClient(value = "upload-server", configuration = TestServiceClient.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(); } } }
在啟動(dòng)了服務(wù)提供方之后,嘗試在服務(wù)消費(fèi)方編寫(xiě)測(cè)試用例來(lái)通過(guò)上面定義的Feign客戶端來(lái)傳文件,比如:
@Test @SneakyThrows public void testHandleFileUpload() { File file = new File("files/aaa.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(testServiceClient.handleFileUpload(multi)); }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。