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

相关推荐
爬山算法29 分钟前
Hibernate(67)如何在云环境中使用Hibernate?
java·后端·hibernate
女王大人万岁1 小时前
Go标准库 io与os库详解
服务器·开发语言·后端·golang
露天赏雪1 小时前
Java 高并发编程实战:从线程池到分布式锁,解决生产环境并发问题
java·开发语言·spring boot·分布式·后端·mysql
短剑重铸之日2 小时前
《SpringCloud实用版》 Seata 分布式事务实战:AT / TCC / Saga /XA
后端·spring·spring cloud·seata·分布式事务
iRuriCatt2 小时前
智慧景区管理系统 | 计算机毕设项目
java·前端·spring boot·vue·毕设
FAFU_kyp2 小时前
RISC0_ZERO项目在macOs上生成链上证明避坑
开发语言·后端·学习·macos·rust
qq_12498707532 小时前
基于springboot的会议室预订系统设计与实现(源码+论文+部署+安装)
java·vue.js·spring boot·后端·信息可视化·毕业设计·计算机毕业设计
女王大人万岁3 小时前
Go语言time库核心用法与实战避坑
服务器·开发语言·后端·golang
J_liaty3 小时前
Spring Boot + MinIO 文件上传工具类
java·spring boot·后端·minio
短剑重铸之日3 小时前
《SpringCloud实用版》Stream + RocketMQ 实现可靠消息 & 事务消息
后端·rocketmq·springcloud·消息中间件·事务消息