当前位置:首页 > Web开发 > 正文

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

2024-03-31 Web开发

在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); }

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

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/42546.html