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

相关推荐
Mikey_n31 分钟前
Spring Boot 注解详细解析:解锁高效开发的密钥
java·spring boot·后端
bing_15832 分钟前
Spring MVC 和 Spring Boot 是如何访问静态资源的?
spring boot·spring·mvc
全职计算机毕业设计1 小时前
SpringBoot Vue MySQL酒店民宿预订系统源码(支付宝沙箱支付)+代码讲解视频
vue.js·spring boot·mysql
Kookoos1 小时前
【实战】基于 ABP vNext 构建高可用 S7 协议采集平台(西门子 PLC 通信全流程)
后端·物联网·c#·.net
帮帮志1 小时前
vue3与springboot交互-前后分离【完成登陆验证及页面跳转】
spring boot·后端·交互
wowocpp1 小时前
idea springboot 配置文件 中文显示
java·spring boot·intellij-idea
柴薪之王、睥睨众生1 小时前
(自用)Java学习-5.8(总结,springboot)
java·开发语言·spring boot·学习·mybatis
{{uname}}9 小时前
利用WebSocket实现实时通知
网络·spring boot·websocket·网络协议
goTsHgo11 小时前
Spring Boot 自动装配原理详解
java·spring boot
炒空心菜菜11 小时前
SparkSQL 连接 MySQL 并添加新数据:实战指南
大数据·开发语言·数据库·后端·mysql·spark