首页 > 解决方案 > Rest-Api 在 Spring Boot 中调用其他 Rest-Api 不工作(多部分文件)

问题描述


我需要你的帮助。我在同一个类中有 2 个 Api 都用于上传文件。我正在尝试使用 of 将文件从 1 个 api 上传到其他 api,RestTemplate但它显示错误。

错误:-由于上述错误,MessageType definition error: [simple type, class java.io.FileDescriptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 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"]) 文件存储 Api 未调用。RestTemplate

API-1:- 文件存储 API

@RequestMapping(value = PathConst.UPLOAD_MULTIPART_FILE, method = RequestMethod.POST)
public ResponseEntity<?> uploadMultipleFiles(@RequestPart("files") @NotNull List<MultipartFile> files) {
   try {
       this.apiResponse = new APIResponse();

    // Note :- 'here this upload file dto help to collect the non-support file info'
    List<UploadFileDto> wrongTypeFile = files.stream().
            filter(file -> {
                return !isSupportedContentType(file.getContentType());
            }).map(file -> {
                UploadFileDto wrongTypeFileDto = new UploadFileDto();
                wrongTypeFileDto.setSize(String.valueOf(file.getSize()));
                wrongTypeFileDto.setFileName(file.getOriginalFilename());
                wrongTypeFileDto.setContentType(file.getContentType());
                return wrongTypeFileDto;
            }).collect(Collectors.toList());

    if(!wrongTypeFile.isEmpty()) { throw new FileStorageException(wrongTypeFile.toString()); }

    this.apiResponse.setReturnCode(HttpStatus.OK.getReasonPhrase());
    this.apiResponse.setMessage("File Store Success full");
    this.apiResponse.setEntity(
        files.stream().map(file -> {
            String fileName = this.fileStoreManager.storeFile(file);
            String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path(PathConst.FILE + PathConst.DOWNLOAD_FILE).path(fileName).toUriString();

            UploadFileDto uploadFile = new UploadFileDto();
            uploadFile.setFileName(fileName);
            uploadFile.setUrl(fileDownloadUri);
            uploadFile.setSize(String.valueOf(file.getSize()));

            return uploadFile;
        }).collect(Collectors.toList()));

}catch (Exception e) {
    System.out.println("Message" + e.getMessage());

    this.errorResponse = new ExceptionResponse();
    this.errorResponse.setErrorCode(HttpStatus.BAD_REQUEST.getReasonPhrase());
    this.errorResponse.setErrorMessage("Sorry! Filename contains invalid Type's,");
    this.errorResponse.setErrors(Collections.singletonList(e.getMessage()));
    return new ResponseEntity<ExceptionResponse>(this.errorResponse, HttpStatus.BAD_REQUEST);

}

return new ResponseEntity<APIResponse>(this.apiResponse, HttpStatus.OK);

}

API-2:- 带有图像文件列表的产品商店 API

    @RequestMapping(value = "/save/product", method = RequestMethod.POST)
    public ResponseEntity<?> saveProduct(@Valid @RequestPart("request") ProductDto productDto, @RequestPart("files") @NotNull List<MultipartFile> files) {
        try {
            this.apiResponse = new APIResponse();
            this.restTemplate = new RestTemplate();

            if(!files.isEmpty()) { new NullPointerException("List of File Empty"); }
            // call-api of File controller
            try {
                // file's

                MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
                files.stream().forEach(file -> { body.add("files", file); });

                // header-type
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);
                // request real form
                HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(body, headers);
                // request-url
                this.RESOURCE_URL = ServletUriComponentsBuilder.fromCurrentContextPath().path(PathConst.FILE + PathConst.UPLOAD_MULTIPART_FILE).toUriString();
                // response-result
                System.out.println(this.restTemplate.exchange(this.RESOURCE_URL, HttpMethod.POST, request, Object.class).getStatusCode());
//                if(!response.getStatusCode().equals(200)) {
//                    // error will send
//                }

            }catch (NullPointerException e) {
                throw new NullPointerException("Product Image's Not Save Scuessfully. " + e);
            }

        }catch (Exception e) {
            System.out.println("Message" + e.getMessage());
            this.errorResponse = new ExceptionResponse();
            this.errorResponse.setErrorCode(HttpStatus.NO_CONTENT.getReasonPhrase());
            this.errorResponse.setErrorMessage(e.getMessage());
            return new ResponseEntity<ExceptionResponse>(this.errorResponse, HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<APIResponse>(this.apiResponse, HttpStatus.OK);
    }

主要代码:-

try {
    // file's

    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
    files.stream().forEach(file -> { body.add("files", file); });

    // header-type
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    // request real form
    HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(body, headers);
    // request-url
    this.RESOURCE_URL = ServletUriComponentsBuilder.fromCurrentContextPath().path(PathConst.FILE + PathConst.UPLOAD_MULTIPART_FILE).toUriString();
    // response-result
    System.out.println(this.restTemplate.exchange(this.RESOURCE_URL, HttpMethod.POST, request, Object.class).getStatusCode());
         //if(!response.getStatusCode().equals(200)) {
         //   // error will send
         //}

}catch (NullPointerException e) {
    throw new NullPointerException("Product Image's Not Save Scuessfully. " + e);
}

标签: javaspring-mvcspring-boot

解决方案


我遇到了同样的问题,但是使用下面的代码我修复了它。

@RequestMapping("/upload")
public void postData(@RequestParam("file") MultipartFile file) throws IOException {
      String url = "https://localhost:8080/upload";
     MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
      bodyMap.add("file", new FileSystemResource(convert(file)));
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.MULTIPART_FORM_DATA);
      HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);
      RestTemplate restTemplate = new RestTemplate();
      ResponseEntity<String> response = restTemplate.exchange(url,
              HttpMethod.POST, requestEntity, String.class);
    }
  public static File convert(MultipartFile file)
  {    
    File convFile = new File(file.getOriginalFilename());
    try {
        convFile.createNewFile();
          FileOutputStream fos = new FileOutputStream(convFile); 
            fos.write(file.getBytes());
            fos.close(); 
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

    return convFile;
 }

推荐阅读