springcloud Fegin을 사용하여 파일 업로드 오류 보고Could not write request: no suitable Http Message Converter found for request

7319 단어 springboot

 


질문


springcloud 마이크로 서비스에서fastdfs 파일 서버를 통해 파일을 업로드하는 등feign을 사용하여 파일을 업로드하는 서비스를 호출해야 합니다.
1.fegin의 인터페이스 설정(서비스 강등 코드: 약~)
@FeignClient(value = "XXXXXXXX-XXXXX-PROVIDER", fallbackFactory = XxxxxxClientFallbackFactory.class)
public interface XxxxxxClientService {
    /**
     *     
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/xxxxx/xxxxx/saveFile", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result saveFile(@RequestPart("file") MultipartFile file) throws Exception;
}

2. 서비스 입구 코드:
    /**
     *     
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/xxxxx/xxxxx/saveFile", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result saveFile(@RequestPart("file") MultipartFile file) throws Exception {
        try {
            return xxxxxxClientService.saveFile(file);//fegin      
        } catch (Exception e) {
            log.error("~~~~", e);
        }
        return Result.error();

    }

3. 파일 업로드 서비스(이 서비스에 단독으로 방문하여 파일을 업로드 성공~)
@RequestMapping(value = "/xxxxxx/saveFile", method = RequestMethod.POST)
    public Result saveFile(@RequestPart("file") MultipartFile file) throws Exception {
        if (file == null) {
            return new Result().put("code", "900001").put("msg", "   ,      ").put("imgUrl", "");
        } else {
            String imgUrl = dfsClient.uploadFile(file); //  fastdfs    
            return new Result().put("code", "0").put("msg", "      ").put("imgUrl", imgUrl);
        }
    }

4.FastDFS 파일 서버 구성: (종속, 구성 등)
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;


@Component
public class FastDFSClientWrapper {

    private static final Logger log = LoggerFactory.getLogger(FastDFSClientWrapper.class);

    @Autowired
    private FastFileStorageClient storageClient;

    @Value("${fdfs.resHost}")
    private String resHost;

    @Value("${fdfs.storagePort}")
    private String storagePort;

    /**
     *     
     *
     * @param file     
     * @return       
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResAccessUrl(storePath);
    }

    /**
     *               
     *
     * @param content           
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null);
        return getResAccessUrl(storePath);
    }

    //       URL  
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = "http://" + resHost
                + ":" + storagePort + "/" + storePath.getFullPath();
        return fileUrl;
    }

    /**
     *     
     *
     * @param fileUrl       
     * @return
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            log.warn(e.getMessage());
        }
    }

}

포털 서비스를 통해 액세스하면 다음과 같은 오류 메시지가 표시됩니다.
Caused by: feign.codec.EncodeException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile] and content type [multipart/form-data]
	at org.springframework.cloud.netflix.feign.support.SpringEncoder.encode(SpringEncoder.java:113) ~[spring-cloud-netflix-core-1.3.1.RELEASE.jar:1.3.1.RELEASE]
	at feign.ReflectiveFeign$BuildEncodedTemplateFromArgs.resolve(ReflectiveFeign.java:351) ~[feign-core-9.5.0.jar:na]
	at feign.ReflectiveFeign$BuildTemplateByResolvingArgs.create(ReflectiveFeign.java:213) ~[feign-core-9.5.0.jar:na]
	at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:72) ~[feign-core-9.5.0.jar:na]
	at feign.hystrix.HystrixInvocationHandler$1.run(HystrixInvocationHandler.java:108) ~[feign-hystrix-9.5.0.jar:na]
	at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:302) ~[hystrix-core-1.5.12.jar:1.5.12]
	at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:298) ~[hystrix-core-1.5.12.jar:1.5.12]
	at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46) ~[rxjava-1.1.10.jar:1.1.10]
	... 26 common frames omitted

해결 방법:


1、pom.xml에 의존 추가하기

            io.github.openfeign.form
            feign-form
            3.0.3
        
        
            io.github.openfeign.form
            feign-form-spring
            3.0.3
        

2. 구성 클래스를 추가합니다.
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;


@Configuration
public class FeignMultipartSupportConfig {

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

    @Bean
    public feign.Logger.Level multipartLoggerLevel() {
        return feign.Logger.Level.FULL;
    }
}

3. fegin의 방식으로 파일을 업로드하는 서비스를 호출한다.
{"msg":"      ","fileUrl":"http://xxx.xxx.xxx.xxx/group1/M00/00/00/Co1uzFzWlz6AZWC2AAltu9tu2nA760.png","code":"0"}

횡단보도 문제를 해결할 수 있기를 바랍니다.

초보자 1개, 벽돌을 환영합니다~

좋은 웹페이지 즐겨찾기