繁体   English   中英

如何通过rest api上传多部分文件?

[英]How to upload multipart file through rest api?

我知道如何从邮递员上传多部分文件,但如何通过 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

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

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

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

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

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 );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM