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

相关推荐
master_hl几秒前
基于 Kafka 与时间轮实现高性能延迟消息
后端
a***131417 分钟前
python的sql解析库-sqlparse
android·前端·后端
s***558130 分钟前
Skywalking介绍,Skywalking 9.4 安装,SpringBoot集成Skywalking
spring boot·后端·skywalking
至此流年莫相忘39 分钟前
Springboot入参校验实战:使用 javax.validation 优雅处理参数校验
spring boot
IT_陈寒1 小时前
Redis深度优化:10个让你的QPS提升50%的关键配置解析
前端·人工智能·后端
烤麻辣烫2 小时前
黑马程序员苍穹外卖(新手) DAY3
java·开发语言·spring boot·学习·intellij-idea
武子康2 小时前
大数据-157 Apache Kylin 全面指南:MOLAP 架构、Hive/Kafka 实战与实时 OLAP 落地
大数据·后端·apache kylin
ssshooter2 小时前
传参优于外部变量
前端·后端·面试
qq_22589174662 小时前
基于Python+Django餐饮评论大数据分析与智能推荐系统 毕业论文
开发语言·后端·python·信息可视化·数据分析·django
百***49002 小时前
基于SpringBoot和PostGIS的各省与地级市空间距离分析
java·spring boot·spring