restTemplate.postForObject() MultipartFile(上傳檔案)
阿新 • • 發佈:2021-08-11
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檔案"); } }