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

相关推荐
羊小猪~~4 分钟前
算法/力扣--栈与队列经典题目
开发语言·c++·后端·考研·算法·leetcode·职场和发展
晨非辰19 分钟前
Git版本控制速成:提交三板斧/日志透视/远程同步15分钟精通,掌握历史回溯与多人协作安全模型
linux·运维·服务器·c++·人工智能·git·后端
Moment19 分钟前
如果想转 AI 全栈?推荐你学一下 Langchain!
前端·后端·面试
顾北1220 分钟前
Elasticsearch DSL 从入门到实战:全文检索 + 地理查询 + SpringBoot 整合全攻略
后端·elasticsearch
大鸡腿同学20 分钟前
AI编程时代来临
后端
啥都想学点23 分钟前
从 Flutter 前端到 Spring Boot 后端:2026 年技术栈落地路线图(实战版)
前端·spring boot·flutter
七夜zippoe27 分钟前
云原生Java应用部署:将Spring Boot应用迁移至Kubernetes完整指南
java·spring boot·docker·云原生·kuberbertes
mygljx4 小时前
SpringBoot+Mybatis-plus实现分页查询(一看就会)
spring boot·mybatis·状态模式
小码哥_常7 小时前
别再被误导!try...catch性能大揭秘
后端