日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

org.springframework.web.client.RestTemplate 上傳文件無法獲取文件信息

作者:魯尼的小寶貝 更新時間: 2022-03-15 編程語言

使用RestTemplate 模擬上傳文件的時候,不能在接收端接收到文件的字節。

/**
     * 上傳文件
     *
     * @param name
     * @param bytes
     * @return
     */
    public Long updateBytes(String name, byte[] bytes) throws XyidcException {
        //設置請求頭
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setConnection("Keep-Alive");
        headers.setCacheControl("no-cache");

        //設置請求體,注意是LinkedMultiValueMap
        ByteArrayResource fileSystemResource = new ByteArrayResource(bytes){
            @Override
            public String getFilename() {
                return name;
            }
        };
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", fileSystemResource);
        form.add("filename", name);

        //用HttpEntity封裝整個請求報文
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

        String s = restTemplate.postForObject("http://" + apiServerName + "/" + apiServerName + "/xyidc-basic/v1/file/upload", files, String.class);
        JSONObject result = JSONObject.parseObject(s);
        List<FileUploadRespVo> fileUploadRespVos = Lists.newArrayList();
        if (SystemEnums.SUCCESS.getCode().equals(result.getString("code"))) {
            JSONArray datas = result.getJSONArray("data");
            for (Object data : datas) {
                fileUploadRespVos.add(JSONObject.parseObject(JSONObject.toJSONString(data), FileUploadRespVo.class));
            }
        }
        if (CollectionUtils.isEmpty(fileUploadRespVos)) {
            logger.error(s);
            throw new XyidcException("文件上傳報錯了,請查看一下");
        }
        return fileUploadRespVos.get(0).getFileId();
    }

需要重寫ByteArrayResource的GetFilename接口

原文鏈接:https://blog.csdn.net/poem_2010/article/details/109594231

欄目分類
最近更新