Feign进行文件上传+表单调用

Feigin默认是不支持文件上传和表单提交的,须要作一些配置才能支持。java

一、feign依赖web

 图中红色为form支持必须的jar。spring

 

二、添加自定义Encoder类:api

import static java.util.Collections.singletonMap;

import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.springframework.web.multipart.MultipartFile;

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.form.spring.SpringFormEncoder;
import lombok.val;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

/**
 * @author roger yang
 * @date 10/22/2019
 */
public class MultipartEncoder extends SpringFormEncoder {
    
    @SuppressWarnings("unchecked")
    @Override
    public void encode (Object object, Type bodyType, RequestTemplate template) throws EncodeException {
        if (((ParameterizedTypeImpl) bodyType).getRawType().equals(Map.class)) {
            val data = (Map<String, Object>) object;
            Set<String> nullSet = new HashSet<>();
            for (Map.Entry<String, Object> entry : data.entrySet()) {
                if (entry.getValue() == null) {
                    nullSet.add(entry.getKey());
                }
            }
            for (String s : nullSet) {
                data.remove(s);
            }
            super.encode(data, MAP_STRING_WILDCARD, template);
            return;
        } else 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);
    }
}

为何要自定义呢?由于SpringFormEncoder这个类的源码里只对MultipartFile作了特殊处理,并未对MultipartFile[]数组进行处理,在传递多个文件时会报错。数组

  @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);
  }

另外,咱们为了让文件和表单一块儿在http的body里一块儿传输,全部咱们将他们都封装到map里统一处理。app

 

三、feign接口类:ide

import java.util.Map;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.longge.common.GlobalResponse;

/**
 * @author: tomfang
 * @description: Notification api
 * post with MULTIPART_FORM_DATA_VALUE
 * you client feign config:
 * -------------------------------------------------------------------
 *  import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.context.annotation.Bean;
    
    import com.longge.api.NotificationService;
    
    import feign.codec.Encoder;
    import com.longge.config.MultipartEncoder;
    
    @FeignClient(value = "notification-service", configuration = NotificationServiceFeign.FeignSimpleEncoderConfig.class)
    public interface NotificationServiceFeign extends NotificationMultipartService {
        class FeignSimpleEncoderConfig {
            
            @Bean
            public Encoder encoder(){
                return new MultipartEncoder();
            }
        }
    }
 * ---------------------------------------------------------------------
 * @date: 17:24 2019/7/3
 **/
@RequestMapping(value = "/v1/api")
public interface NotificationMultipartService {

    /**
     * common email channel ,use to send common email
     *
     * @param data
     *     map key have: 
     *          attachfile       -->          MultipartFile[]
     *          com.longge.dto.EmailDto.FieldName --- >   value
     *          
     * eg:
     *  Map<String, Object> data = new HashMap<>();
        data.put("attachfile", new MultipartFile[] {file});
        data.put("from", emailDto.getFrom());
        data.put("to", emailDto.getTo());
        data.put("bodyText", emailDto.getBodyText());
        data.put("subject", emailDto.getSubject());
     * @return GlobalResponse<Long>  email id
     */
    @RequestMapping(value = "/send_mail", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    GlobalResponse<String> sendMail(Map<String, Object> data);
}

其中为了支持 form请求,须要对此feign进行单独的配置:post

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;

import com.longge.api.NotificationMultipartService;

import feign.codec.Encoder;

@FeignClient(value = "notification-service", configuration = NotificationServiceFeign.FeignSimpleEncoderConfig.class)
public interface NotificationServiceFeign extends NotificationMultipartService {
    class FeignSimpleEncoderConfig {
        @Bean
        public Encoder encoder() {
            return new MyEncoder();
        }
    }
}

 

四、服务实现类ui

@RequestMapping(value = "/v1/api/send_mail", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = {MediaType.APPLICATION_JSON_VALUE})
public GlobalResponse<String> sendMail(@RequestParam(value = "attachfile", required = false) MultipartFile[] attachfile, EmailDto emailDto) {
    // TODO
}

 

五、EmailDto属性spa

private String from;
private String to;
private String subject;
private String bodyText;
private String bodyHtml;

 

感谢:https://blog.csdn.net/ytzzh0726/article/details/79731343 

相关文章
相关标签/搜索