@PostMapping("uploadFile")
public BaseResponseBean<List<VO>> uploadFile(@RequestParam("file") MultipartFile multiFile) {
return new BaseResponseBean(uploadFileFacadeService.uploadFile(multiFile));
}
@Override
public List<VO> uploadFile(MultipartFile multiFile) {
if (Objects.isNull(multiFile)) {
throw new CustomException(FILE_TYPE_ERROR);
}
ByteArrayResource fileAsResource = null;
try {
fileAsResource = new ByteArrayResource(multiFile.getBytes()) {
@Override
public String getFilename() {
return multiFile.getOriginalFilename();
}
@Override
public long contentLength() {
return multiFile.getSize();
}
};
} catch (Exception e) {
log.error(" ByteArrayResource error,{}", e);
}
HttpHeaders headers = Utils.getRequestHeaders();
headers.remove(HttpHeaders.CONTENT_TYPE);
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
params.add(“file”, fileAsResource);
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(params, headers);
String requestUrl = “http://后端接口地址”;
log.info("uploadFile,requestUrl:{},headers:{},params:{}", requestUrl, headers, params);
ResponseEntity<String> response = restTemplate.postForEntity(requestUrl, httpEntity, String.class);
log.info("uploadFile,requestUrl:{},headers:{},response:{}", requestUrl, headers, JSON.toJSONString(response));
JSONObject responseBody = JSONObject.parseObject(response.getBody());
if (response.getStatusCode() != HttpStatus.OK || Objects.isNull(responseBody)) {
throw new CustomException(REQUEST_ERROR, REQUEST_ERROR.getMessage());
}
if (!responseBody.getString("code").equals(RequestTypeEnum.TYPE.getName())) {
log.info("接口失败:{}", JSON.toJSONString(responseBody));
throw new CustomException(SERVER_ERROR, responseBody.getString("msg"));
}
JSONArray resultArray = responseBody.getJSONArray(RESULT_DATA);
if (CollectionUtils.isEmpty(resultArray)) {
return new ArrayList<>();
}
List<VO> list = JSONObject.parseArray(resultArray.toJSONString(), VO.class);
return list;
}
java 实现类似于postman上传文件
于 2024-07-26 14:17:13 首次发布