文件上传spring spring feign client

时间:2017-10-02 08:50:39

标签: java microservices spring-cloud multipart feign

当使用spring cloud netflix的假客户端从一个微服务发送到另一个微服务的帖子请求时,我在Postman中收到以下错误:

{
"timestamp": 1506933777413,
"status": 500,
"error": "Internal Server Error",
"exception": "feign.codec.EncodeException",
"message": "Could not write JSON: No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile[\"inputStream\"]->java.io.FileInputStream[\"fd\"])",
"path": "/attachments"
}

我的eclipse控制台显示以下异常:

  

com.fasterxml.jackson.databind.JsonMappingException:找不到类java.io.FileDescriptor的序列化程序,并且没有发现创建BeanSerializer的属性(为了避免异常,请禁用SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过引用链:org.springframework.web .multipart.support.StandardMultipartHttpServletRequest $ StandardMultipartFile [ “的inputStream”] - > java.io.FileInputStream中[ “FD”])       在com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:284)〜[jackson-databind-2.8.9.jar:2.8.9]       at com.fasterxml.jackson.databind.SerializerProvider.mappingException(SerializerProvider.java:1110)~ [jackson-databind-2.8.9.jar:2.8.9]       在com.fasterxml.jackson.databind.SerializerProvider.reportMappingProblem(SerializerProvider.java:1135)〜[jackson-databind-2.8.9.jar:2.8.9]       at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:69)〜[jackson-databind-2.8.9.jar:2.8.9]       at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:32)〜[jackson-databind-2.8.9.jar:2.8.9]       在com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704)〜[jackson-databind-2.8.9.jar:2.8.9]       在com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:689)~ [jackson-databind-2.8.9.jar:2.8.9]       at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)~ [jackson-databind-2.8.9.jar:2.8.9]       在com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704)〜[jackson-databind-2.8.9.jar:2.8.9]       在com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:689)~ [jackson-databind-2.8.9.jar:2.8.9]       at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)~ [jackson-databind-2.8.9.jar:2.8.9]       在com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292)~ [jackson-databind-2.8.9.jar:2.8.9]       在com.fasterxml.jackson.databind.ObjectWriter $ Prefetch.serialize(ObjectWriter.java:1429)~ [jackson-databind-2.8.9.jar:2.8.9]       在com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:951)〜[jackson-databind-2.8.9.jar:2.8.9]

更新1

这是我的假装界面:

@FeignClient(name="attachment-service", fallback=AttachmentHystrixFallback.class)
public interface AttachmentFeignClient {

@RequestMapping("upload")
void upload(@RequestPart(name="file") MultipartFile file, @RequestParam(name="attachableId") Long attachableId, 
        @RequestParam(name="className") String className, @RequestParam(name="appName") String appName);

这是主要的微服务控制器:

@RestController
public class AttachmentController implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = -4431842080646836475L;

@Autowired
AttachmentService attachmentService;

@RequestMapping(value = "attachments", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void upload(@RequestPart MultipartFile file, @RequestParam Long attachableId, @RequestParam String className, @RequestParam String appName) throws Exception {
    attachmentService.uploadFile(file, attachableId, className, appName);
}

}

我肯定在这里缺少某种序列化器 任何建议将不胜感激!
感谢

3 个答案:

答案 0 :(得分:8)

在搜索解决方案几天后,我发现了这一点。你应该开始为春天依赖添加假装形式:

<dependency>
   <groupId>io.github.openfeign.form</groupId>
   <artifactId>feign-form-spring</artifactId>
   <version>3.3.0</version>
</dependency

然后你的假装客户需要这个弹簧形式编码器:

@FeignClient(name="attachment-service",  configuration = {AttachmentFeignClient.MultipartSupportConfig.class}
 fallback=AttachmentHystrixFallback.class)
public interface AttachmentFeignClient {

@RequestMapping(value= {"upload"}, consumes = {"multipart/form-data"})
void upload(@RequestPart(name="file") MultipartFile file, @RequestParam(name="attachableId") Long attachableId, 
        @RequestParam(name="className") String className, @RequestParam(name="appName") String appName);

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

我希望它会帮助别人。

答案 1 :(得分:1)

TL; DR
将您的MultiPartFile转换为MultiValueMap。参见下面的示例


@martin-choraine提到的答案是拥有FeignClient方法签名的正确和最佳答案,该签名与您尝试调用的实际端点签名相同。但是,有一种方法不需要您定义FormEncoder或添加任何额外的依赖关系,因为在某些应用程序中,您不允许这样做(企业该死);您所需要做的就是将MultipartFile转换为MultiValueMap,因为标准编码器可以对其进行序列化,所以它可以完美地工作。


要调用的实际端点

@PostMapping(path = "/add", consumes = MULTIPART_FORM_DATA_VALUE, produces = APPLICATION_JSON_VALUE)
 public MyResponseObject add(@RequestParam(name = "username") String username,
                             @RequestPart(name = "filetoupload") MultipartFile file) {
              Do something
}

FeignClient中的POST方法应如下所示

@PostMapping(path = "/myApi/add", consumes = MULTIPART_FORM_DATA_VALUE, 
              produces = APPLICATION_JSON_VALUE)
 public MyResponseObject addFile(@RequestParam(name = "username") String username,
                           @RequestPart(name = "filetoupload") MultiValueMap<String, Object> file);

然后,当您调用addFile时,您应该像这样提供MultiValueMap

public MyResponseObject addFileInAnotherEndPoint(String username, MultipartFile file) throws IOException {

    MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
    ByteArrayResource contentsAsResource = new ByteArrayResource(file.getBytes()) {
        @Override
        public String getFilename() {
            return file.getOriginalFilename();
        }
    };
    multiValueMap.add("filetoupload", contentsAsResource);
    multiValueMap.add("fileType", file.getContentType());
    return this.myFeignClient.addFile(username, multiValueMap);
}

答案 2 :(得分:0)

我在帖子中添加了消耗= MediaType.MULTIPART_FORM_DATA_VALUE,它对我有用。  这是我的伪装客户方法,在前面我使用了formdata

router.post('/', upload.single('file'), (req, res) => {
    return res.status(200).send({
        success: 'true',
        message: 'upload successful'
    })
});

这是我的尖角

@PostMapping(path=Urls.UPLOAD_FILE_IN_LIBELLE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE )
    public void uploadFileInLibelle(
            @RequestParam String processus,
            @RequestParam String level0Name,
            @RequestParam String nomFichier,
            @RequestParam String nomLibelle,
            @RequestParam String anneeFolderName,
            @RequestParam String semaineFolderName,
            @RequestPart   MultipartFile fichier);