SpringBoot RestTemplate 上传文件

SpringBoot RestTemplate 上传文件

复制代码
    @Test
    public void testUpload() throws Exception {
        String url = "http://127.0.0.1/file/upload";
        String filePath = "C:\\temp\\1.png";

        RestTemplate rest = new RestTemplate();
        FileSystemResource resource = new FileSystemResource(new File(filePath));
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("file", resource);
        param.add("fid", "1");

        String string = rest.postForObject(url, param, String.class);

        System.out.println(string);
    }

或者

复制代码
    @Test
    public void testUpload2() throws Exception {

        String url = "http://127.0.0.1/file/upload";
        String filePath = "C:\\temp\\1.png";

        RestTemplate rest = new RestTemplate();
        FileSystemResource resource = new FileSystemResource(new File(filePath));
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("file", resource);
        param.add("fid", "1");

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param);
        ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);

        System.out.println(responseEntity.getBody());

    }

SpringBoot项目 前后端分离 ajax附件上传下载,参考SpringBoot项目 前后端分离 ajax附件上传下载

相关推荐
一个专注写bug的小白猿7 分钟前
.net实现ftp传输文件保姆教程
后端·c#·.net
青皮桔40 分钟前
Java+OpenCV实现图片切割
java·后端·opencv·计算机视觉
lang2015092844 分钟前
Spring Boot JMX与Jolokia监控实战
spring boot
兮动人1 小时前
Spring中@Configuration注解的proxyBeanMethods属性详解
java·后端·spring
zl9798991 小时前
SpringBoot-数据访问之Druid
java·spring boot
Jing_jing_X2 小时前
Spring 自动注入是怎么实现的?从 @Component 到 @Autowired 的完整流程
java·后端·spring
IT_陈寒2 小时前
5个Vue3性能优化技巧,让你的应用提速50% 🚀(附实测对比)
前端·人工智能·后端
00后程序员2 小时前
iOS 26 App 开发阶段性能优化 从多工具协作到数据驱动的实战体系
后端
PFinal社区_南丞2 小时前
从 trace 到洞察:Go 项目的可观测性闭环实践
后端
镜花水月linyi2 小时前
解锁AQS
java·后端·面试