RestTemplate将字符串以文件的方式上传

背景

在java后台将内容拼接为字符串,然后使用RestTemplate将字符串以文件的方式上传到指定接口

思路

使用 RestTemplate 时,将字符串封装为字节流,然后上传

代码

/**
     *  将字符串以文件的方式上传
     *
     * @param url 上传的接口 url
     * @param content 上传的字符串内容
     * @param fileName 文件的名称
     * @param toPath 存放在服务器上的位置
     * @return  RestTemplate 的请求结果
     * @author daleyzou
     */
    public static ResponseEntity<String> postFileData(String url, String content,String fileName, String toPath) {
        RestTemplate client = new RestTemplate();
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("name", fileName);
        param.add("filename", fileName);
        param.add("path", toPath);
        // 构建字节流数组
        ByteArrayResource resource = new ByteArrayResource(content.getBytes()) {
            @Override
            public String getFilename() {
                // 文件名
                return fileName;
            }
        };
        param.add("file", resource);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param,headers);
        return client.exchange(url,HttpMethod.POST, httpEntity, String.class);
    }
posted @ 2019-11-27 20:29  DaleyZou  阅读(453)  评论(0编辑  收藏  举报