restTemplate.postForObject() MultipartFile(上传文件)

        Result result=new Result(true);
            String api = releaseUrl + "/productPrice/ImportExcelData";//远程接口
            ByteArrayResource fileAsResource = new ByteArrayResource(multipartFile.getBytes()) {
                @Override
                public String getFilename() {
                    return multipartFile.getOriginalFilename();
                }

                @Override
                public long contentLength() {
                    return multipartFile.getSize();
                }
            };
            MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
            multipartRequest.add("files", fileAsResource);//注意此处定义的"files"名称需与接口参数名称一致,否则无法拿到数据
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity(multipartRequest, headers);
            result=restTemplate.postForObject(api, files, Result.class);//接口调用

远程接口定义:

  @PostMapping("/ImportExcelData")
    public Result ImportExcelData(@RequestParam List<MultipartFile> files){
        if (files.size()==1) {
            return service.ImportExcelData(files.get(0));
        }else {
            return new Result(false,"请上传单个Excel文件");
        }
    }

 

posted @ 2021-08-11 09:25  小小穿梭机^^  阅读(969)  评论(0编辑  收藏  举报