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文件");
        }
    }

 

上一篇:java代码上传文件到服务器plus版,MultipartFile文件类型,不在涉及本地路径


下一篇:SpringBoot 限制MultipartFile文件大小和格式