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

相关推荐
IT_陈寒2 分钟前
Redis缓存击穿:3个鲜为人知的防御策略,90%开发者都忽略了!
前端·人工智能·后端
uzong37 分钟前
Harness Engineering 是什么?一场新的 AI 范式已经开始
人工智能·后端·架构
唐叔在学习1 小时前
Python桌面端应用最小化托盘开发实践
后端·python·程序员
yuhaiqiang1 小时前
被 AI 忽悠后,开始怀念搜索引擎了?
前端·后端·面试
二闹2 小时前
Python文件读取三巨头你该选择哪一个?
后端·python
彭于晏Yan2 小时前
Spring AI(二):入门使用
java·spring boot·spring·ai
苏三说技术2 小时前
推荐几个牛逼的AI Agent项目
后端
武子康3 小时前
大数据-253 离线数仓 - Airflow 入门与任务调度实战:DAG、Operator、Executor 部署排错指南
大数据·后端·apache hive
IT_陈寒3 小时前
深入理解JavaScript:核心原理与最佳实践
前端·人工智能·后端
树獭叔叔3 小时前
GRPO:比PPO更简单的RLHF算法
后端·aigc·openai