java 实现类似于postman上传文件

@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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值