Spring Cloud中FeignClient實現文件上傳功能

這篇文章主要爲大家詳細介紹了Spring Cloud中FeignClient實現文件上傳功能,具有一定的參考價值,感興趣的小夥伴們可以參考一下

項目概況:Spring Cloud搭的微服務,使用了eureka,FeignClient,現在遇到FeignClient調用接口時不支持上傳文件,

百度到兩種方案,一種是使用feign-form和feign-form-spring庫來做,源碼地址

具體的使用方法是加入maven依賴

<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>

注入SpringFormEncoder類

@Bean
 @Primary
 @Scope("prototype")
 public Encoder multipartFormEncoder() {
 return new SpringFormEncoder();
 }

FeignClient接口裏方法參數是文件類型的要用@RequestPart註解,且要設置ContentType爲multipart/form-data

@ResponseBody
@RequestMapping(value = "/ctstestcase/updateTestCase", method = {RequestMethod.POST}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
 Map<String, Object> updateTestCase(@RequestParam("testcaseId") String testcaseId,
 @RequestParam("name") String name, @RequestParam("assignId") String assignId,
 @RequestParam("areaId") String areaId, @RequestParam("state") Integer state,
 @RequestParam("iterationId") String iterationId,@RequestParam("priority") Integer priority,
 @RequestParam("moduleId") String moduleId, @RequestParam("executionType") Integer executionType,
 @RequestParam("summary") String summary, @RequestParam("tcsteps") String tcsteps,
 @RequestParam("relations") String relations,@RequestParam("attachments") String attachments,
 @RequestPart("files") MultipartFile[] files);

但遇到一個問題,就是不支持文件數組類型,我看了源碼,發現源碼裏底層是有對MultipartFile[]類型的支持的,源碼中有個類叫SpringManyMultipartFilesWriter,是專門針對文件數組類型進行操作的,但是配置到項目裏的SpringFormEncoder類裏卻沒有對文件數組類型的判斷,以致不能支持文件數組的上傳.。

SpringManyMultipartFilesWriter源碼:

@FieldDefaults(level = PRIVATE, makeFinal = true)
public class SpringManyMultipartFilesWriter extends AbstractWriter {
 
 SpringSingleMultipartFileWriter fileWriter = new SpringSingleMultipartFileWriter();
 
 @Override
 public void write (Output output, String boundary, String key, Object value) throws Exception {
 if (value instanceof MultipartFile[]) {
 val files = (MultipartFile[]) value;
 for (val file : files) {
 fileWriter.write(output, boundary, key, file);
 }
 } else if (value instanceof Iterable) {
 val iterable = (Iterable<?>) value;
 for (val file : iterable) {
 fileWriter.write(output, boundary, key, file);
 }
 }
 }
 
 @Override
 public boolean isApplicable (Object value) {
 if (value == null) {
 return false;
 }
 if (value instanceof MultipartFile[]) {
 return true;
 }
 if (value instanceof Iterable) {
 val iterable = (Iterable<?>) value;
 val iterator = iterable.iterator();
 if (iterator.hasNext() && iterator.next() instanceof MultipartFile) {
 return true;
 }
 }
 return false;
 }

SpringFormEncoder源碼:

public class SpringFormEncoder extends FormEncoder {
 
 /**
 * Constructor with the default Feign's encoder as a delegate.
 */
 public SpringFormEncoder () {
 this(new Encoder.Default());
 }
 
 /**
 * Constructor with specified delegate encoder.
 *
 * @param delegate delegate encoder, if this encoder couldn't encode object.
 */
 public SpringFormEncoder (Encoder delegate) {
 super(delegate);
 
 val processor = (MultipartFormContentProcessor) getContentProcessor(MULTIPART);
 processor.addWriter(new SpringSingleMultipartFileWriter());
 processor.addWriter(new SpringManyMultipartFilesWriter());
 }
 
 @Override
 public void encode (Object object, Type bodyType, RequestTemplate template) throws EncodeException {
 if (!bodyType.equals(MultipartFile.class)) {
 super.encode(object, bodyType, template);
 return;
 }
 
 val file = (MultipartFile) object;
 val data = singletonMap(file.getName(), object);
 super.encode(data, MAP_STRING_WILDCARD, template);
 }
}

從上面SpringFormEncoder的源碼上可以看到SpringFormEncoder類構造時把SpringManyMultipartFilesWriter實例添加到了處理器列表裏了,但是在encode方法裏又只判斷了MultipartFile類型,沒有判斷數組類型,這就比較奇怪了,底層有對數組的支持但上層卻缺少了相應判斷,而且在源碼裏的test包裏也沒有對文件數組類型的測試,難道只是encode方法裏漏掉了?還是說那個文件數組的支持有問題?所以encode方法裏纔沒有加入對其的判斷?

於是我先試着對encode方法進行擴展加入對文件數組的判斷,應該就可以支持文件數組的上傳了,於是把SpringFormEncoder類源碼複製出來重命名爲FeignSpringFormEncoder,源碼如下:

public class FeignSpringFormEncoder extends FormEncoder {
 
 /**
 * Constructor with the default Feign's encoder as a delegate.
 */
 public FeignSpringFormEncoder() {
 this(new Encoder.Default());
 }
 
 
 /**
 * Constructor with specified delegate encoder.
 *
 * @param delegate delegate encoder, if this encoder couldn't encode object.
 */
 public FeignSpringFormEncoder(Encoder delegate) {
 super(delegate);
 
 val processor = (MultipartFormContentProcessor) getContentProcessor(MULTIPART);
 processor.addWriter(new SpringSingleMultipartFileWriter());
 processor.addWriter(new SpringManyMultipartFilesWriter());
 }
 
 
 @Override
 public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
 if (bodyType.equals(MultipartFile.class)) {
 val file = (MultipartFile) object;
 val data = singletonMap(file.getName(), object);
 super.encode(data, MAP_STRING_WILDCARD, template);
 return;
 } else if (bodyType.equals(MultipartFile[].class)) {
 val file = (MultipartFile[]) object;
 if(file != null) {
 val data = singletonMap(file.length == 0 ? "" : file[0].getName(), object);
 super.encode(data, MAP_STRING_WILDCARD, template);
 return;
 }
 }
 super.encode(object, bodyType, template);
 }
}

經過測試,已經可以支持文件數組了,完美解決。

這裏再順便說一下當時還百度到另一個解決文件上傳的方案,這個方案就不細說了,直接上我用到的那個開源代碼的地址

這個我試過也是可以解決文件上傳問題的,但問題是FeignClient不能用SpringMVC的註解,得用Feign自帶的註解,也因此我才擴展了第一種方法來做的文件上傳功能。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章