【问题标题】:How to upload multipart file through rest api?如何通过rest api上传多部分文件?
【发布时间】:2021-02-04 09:57:19
【问题描述】:

我知道如何从邮递员上传多部分文件,但如何通过 REST API 来做同样的事情。当我通过邮递员时,消费者 API 工作正常,但在通过 REST 做同样的事情时,它不起作用。

我正在通过这样的 REST 做同样的事情,但它不起作用:

    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

                    MultiValueMap<String, Object> body
                            = new LinkedMultiValueMap<>();
                    body.add("file", file);

                    HttpEntity<MultiValueMap<String, Object>> requestEntity
                            = new HttpEntity<>(body, headers);



                    String serverUrl = "http://localhost:9001/communication/api/messageEngine/event/RECIPT/sendEmailAttachment";

                    ParameterizedTypeReference<ApiResponse<Map<String,Object>>> parameterizedTypeReference =
                            new ParameterizedTypeReference<com.loylty.dataacquisition.model.ApiResponse<Map<String,Object>>>() {};


                    RestTemplate restTemplate = new RestTemplate();
                    try {
                        ResponseEntity<com.loylty.dataacquisition.model.ApiResponse<Map<String,Object>>> result =
                                restTemplate.exchange(serverUrl, HttpMethod.POST, requestEntity, parameterizedTypeReference);
                        if (result.getStatusCode().is2xxSuccessful() == false) {
                            throw new DENotReachableException();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw e;
                    }

目标 API 或消费者 API

     @CrossOrigin
    @RequestMapping(method = RequestMethod.POST, value = "/event/{event}/sendEmailAttachment", consumes = {"multipart/form-data"})
    public ApiResponse<Object> sendReceiptWithAttachment(@RequestPart("file") MultipartFile file, @PathVariable("event") String event) {

        LidsysUtil.messageId.set(String.valueOf(new Date().getTime()));

        MessageTracker tracker = new MessageTracker(LidsysUtil.messageId.get(), event);
        LidsysUtil.tracker.set(tracker);
        LOGGER.info("Executing Message Id : {} ", LidsysUtil.messageId.get());
        LOGGER.info("Request received for event : {}", event);
       // LOGGER.info("Request Body : {}", LidsysUtil.displayJSON(requestBody));
        Map<String, Object> request = messageEngineService.initiateEmailwithAttachmentV2( file, event);

        return new ApiResponse<>(APIResponseKey.ALL_GOOD, messageEngineService.execute(request, event), null);
    }

当我尝试使用 REST api 时出现以下异常

源微服务异常

020-10-21 19:11:18,237 [ERROR]---[DirectJDKLog.java]---[http-nio-8010-exec-2]: Servlet.service() for servlet [dispatcherServlet] in context with path [/dataacquisition] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 400 null] with root cause
org.springframework.web.client.HttpClientErrorException: 400 null

目标微服务异常

2020-10-21 19:11:17,445 [ERROR]---[HttpLoggingFilter.java]---[http-nio-9001-exec-10]: null

【问题讨论】:

  • 当你说它不起作用时,它是否会打印出任何有意义的信息来帮助理解问题?像个例外?
  • @EvrisTzam 是的,它可以打印,但没有多大帮助。
  • 请更新您的问题并添加它。
  • @EvrisTzam 更新异常

标签: java rest file-upload multipartform-data


【解决方案1】:

当您实例化ParameterizedTypeReference 对象时,为什么要以两种不同的方式引用ApiResponse? (您既使用简单名称,又使用全限定名称com.loylty.dataacquisition.model.ApiResponse)这是否意味着它们可能是两个不同的类?

此外,在消费者方面,您已声明sendReceiptWithAttachment() 方法返回ApiResponse&lt;Object&gt;,而不是ApiResponse&lt;Map&lt;String,Object&gt;&gt;

确保消费者和生产者同步。

【讨论】:

    【解决方案2】:

    我找到了解决方案,在地图中我添加了文件而不是它需要的资源类型

    MultiValueMap<String, Object> body
                            = new LinkedMultiValueMap<>();
                    body.add("file", file);
    

    解决方案

     Resource rfile = new FileSystemResource(file)
     MultiValueMap<String, Object> body
                            = new LinkedMultiValueMap<>();
                    body.add("file", rfile );
    

    【讨论】:

      猜你喜欢
      • 2018-08-06
      • 2016-04-23
      • 1970-01-01
      • 2018-10-10
      • 2023-03-10
      • 2019-07-25
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      相关资源
      最近更新 更多