首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rest-Api调用Spring boot中的其他Rest-Api不起作用(Multipart-File)

Rest-Api调用Spring boot中的其他Rest-Api不起作用(Multipart-File)
EN

Stack Overflow用户
提问于 2018-09-03 23:10:57
回答 2查看 5.8K关注 0票数 1

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

错误:-由于上述错误,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

代码语言:javascript
复制
@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:- Product Store Api,带镜像文件列表

代码语言:javascript
复制
    @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);
    }

主代码:-

代码语言:javascript
复制
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);
}
EN

回答 2

Stack Overflow用户

发布于 2018-11-06 13:29:44

我也面临着同样的问题,但我使用下面的代码解决了这个问题。

代码语言:javascript
复制
@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;
 }
票数 7
EN

Stack Overflow用户

发布于 2018-09-04 18:02:13

我通过添加这些代码行来解决这个问题

代码语言:javascript
复制
files.stream().forEach(file -> {
   System.out.println(file.getOriginalFilename());
   Resource resouceFile = new FileSystemResource(file.getBytes(), file.getOriginalFilename());
   body.add("files",  resouceFile);
});


public static class FileSystemResource extends ByteArrayResource {

    private String fileName;

    public FileSystemResource(byte[] byteArray , String filename) {
        super(byteArray);
        this.fileName = filename;
    }

    public String getFilename() { return fileName; }
    public void setFilename(String fileName) { this.fileName= fileName; }

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52152337

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档