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附件上传下载

相关推荐
q***44158 分钟前
Spring Security 新版本配置
java·后端·spring
计算机毕设匠心工作室11 分钟前
【python大数据毕设实战】强迫症特征与影响因素数据分析系统、Hadoop、计算机毕业设计、包括数据爬取、数据分析、数据可视化、机器学习、实战教学
后端·python·mysql
h***047715 分钟前
SpringBoot集成Flink-CDC,实现对数据库数据的监听
数据库·spring boot·flink
o***741717 分钟前
Springboot中SLF4J详解
java·spring boot·后端
雨中散步撒哈拉29 分钟前
18、做中学 | 初升高 | 考场一 | 面向过程-家庭收支记账软件
开发语言·后端·golang
韩立学长1 小时前
【开题答辩实录分享】以《智慧物业管理系统的设计与实现》为例进行答辩实录分享
java·后端·mysql
d***95622 小时前
springboot接入deepseek深度求索 java
java·spring boot·后端
iOS开发上架哦2 小时前
Swift中对象实例方法名混淆问题详细解决方法
后端
零日失眠者2 小时前
【文件管理系列】003:重复文件查找工具
后端·python
哈哈哈笑什么2 小时前
多级缓存框架(Redis + Caffeine)完整指南
redis·后端