Feign 의 멀 티 파 트 파일 전송 구덩이

멀 티 파 트 파일 전송
1.의존 도 추가

<dependency>
      <groupId>io.github.openfeign.form</groupId>
        <artifactId>feign-form</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>io.github.openfeign.form</groupId>
        <artifactId>feign-form-spring</artifactId>
        <version>3.3.0</version>
    </dependency>
2.설정 클래스 추가

@Configuration
public class FeignMultipartConfig {
    @Bean
    @Primary
    @Scope("prototype")
    public SpringFormEncoder multipartFormEncoder() {
        return new SpringFormEncoder();
    }
    @Bean
    public feign.Logger.Level multipartLoggerLevel() {
        return feign.Logger.Level.FULL;
    }
}
3.인터페이스 작성
@FeignClient 설정 클래스 사용
@PostMapping 설정

consumes = MediaType.MULTIPART_FORM_DATA_VALUE
@RequestPart()를 사용 하고@RequestParam()을 사용 할 수 없습니다.

@FeignClient(value = "face-service",configuration = FeignMultipartConfig.class)
public interface FaceClient {
 @PostMapping(value = "/search/student", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    ResponseBase<SearchStudentFaceVO> searchStudentFace(@RequestPart("file") MultipartFile file);
}
feign 은 인자 MultipartFile(파일)의 해결 을 정상적으로 전달 할 수 없습니다.
이전 작업 중 에 업무 장면 이 있 었 습 니 다.파일 을 MultipartFile 로 서비스 간 호출(Feign 사용)해 야 합 니 다.이 기록 에서 밟 은 구덩이 입 니 다.
주의해 야 할 것 은 기본 springcloud 자체 가 져 온 spring-cloud-starter-openfeign 을 사용 하면 파일 전달 이 지원 되 지 않 습 니 다.
인터넷 에 feign-form 과 feign-form-spring 이 지원 하 는 jar 가방 을 많이 사용 하고 SpringFormEncoder 를 설정 하 는 것 을 보 았 습 니 다.하지만 시도 해 보 았 습 니 다.성공 하지 못 했 습 니 다.마지막 으로 다른 방법 을 사 용 했 습 니 다.여기에 기록 하 세 요.
방법 1:외부 의존 사용

 <dependency>
            <groupId>io.github.openfeign.form</groupId>
            <artifactId>feign-form</artifactId>
            <version>3.3.0</version>
        </dependency>
 
        <dependency>
            <groupId>io.github.openfeign.form</groupId>
            <artifactId>feign-form-spring</artifactId>
            <version>3.3.0</version>
        </dependency>
새 설정 클래스:

package com.jsyd.ict.ictservicemanager.configuration;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.context.annotation.Configuration;
/**
 *        feignFormEncoder        encoder
 *         multipartFile    
 * @author wangyang
 * @version 1.0
 * @date 2021/4/13 19:13
 */
@Configuration
public class MultipartSupportConfig {
    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;
    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }
}
feign 인터페이스 설정:

package com.jsyd.ict.ictservicemanager.feign;
import com.jsyd.ict.ictservicemanager.util.resp.RespUtil;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
/**
 *      
 *
 * @author wangyang
 * @version 1.0
 * @date 2021/3/11 21:01
 */
@FeignClient(name = "ict-service-capacity", configuration = MultipartSupportConfig.class)
public interface CapacityFeign {
    @RequestMapping(value = "contentAudit/baiduImgAuditByFile", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    RespUtil baiduImgAuditByFile(@RequestPart(value = "file") MultipartFile file);
}
메모:파일 전송 은@RequestPart()설명 을 사용 해 야 합 니 다.
서버:

    @RequestMapping(value = "/baiduImgAuditByFile", method = RequestMethod.POST)
    public RespUtil baiduImgAuditByFile(@RequestParam("file") MultipartFile file)  {
  //   service
        return null;
    }
그 결과 이렇게 하면 결 과 를 얻 지 못 하고 한참 동안 연 구 했 는데 급 하 게 연 조 를 해 야 하기 때문에 계속 추적 하지 않 았 고 깊이 연구 할 시간 이 있 었 다.
나중에 아래 의 방법 을 사용 하여 성공 적 으로 인삼 을 전달 하 였 다.
방법 2:HttpServletRequest 로 가 져 오기
이 동작 은 필요 하지 않 습 니 다.즉,가 져 올 필요 도 없고 파일 을 만 들 필요 도 없습니다.서버 에서 HttpServletRequest 를 통 해 설정 해 야 합 니 다.
HttpServletRequest 설정 사용:
의사 코드 는 다음 과 같 습 니 다:

    @RequestMapping(value = "/baiduImgAuditByFile", method = RequestMethod.POST)
    public RespUtil baiduImgAuditByFile(MultipartFile file, HttpServletRequest request) {
        if (file == null) {
            //            MultipartFile     
            String contentType = request.getContentType();
            if (contentType != null && contentType.toLowerCase().startsWith("multipart/")) {
                MultipartHttpServletRequest multipartRequest =
                        WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
                if (multipartRequest != null) {
                    MultiValueMap<String, MultipartFile> multiFileMap = multipartRequest.getMultiFileMap();
                    for (Map.Entry<String, List<MultipartFile>> entry : multiFileMap.entrySet()) {
                        file = entry.getValue().get(0);
                    }
                }
            }
        }
        //       
        return null;
    }
주로 다음 과 같은 그림 을 설명 한다.

즉,HttpServletRequest 를 통 해 파일 을 가 져 오지 못 하 더 라 도 특수 처리 하여 파일 을 가 져 올 수 있 습 니 다.
이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기