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

相关推荐
神奇小汤圆2 分钟前
字节二面:10亿数据毫秒级查手机尾号后4位,答不出“异构索引”直接挂?
后端
IT_Octopus6 分钟前
Spring Boot 线程池关闭:destroyMethod 的作用与最佳实践
java·spring boot·后端
Leslie1656 分钟前
用 Reactor 和 Linux 命名管道实现一个本地事件总线
后端
一只叫煤球的猫38 分钟前
ThreadForge 源码解读三:从任务执行到并发编排,ScopeJoiner 是怎么工作的?
后端·性能优化·开源
无限压榨切图仔1 小时前
从 Claude Code 切到 Codex:我用 Agent、Skills、MCP 做完了一个内容运营工具
前端·后端
董员外1 小时前
RAG 系统进化论(一):纵览 RAG 的发展历程
前端·人工智能·后端
Yao8061 小时前
MyBatis-Plus LambdaQueryWrapper实战:告别手写SQL
后端
街头小霸王6261 小时前
微服务项目common配置文件模板
后端
Conan在掘金1 小时前
ArkTS 进阶之道(17):@Extend 专属属性扩展边界——为啥能收 fontSize 专属属性
后端
霸道流氓气质2 小时前
SpringBoot中事务内同步处理 + 事务后异步调用外部系统的通用模式示例
java·spring boot·后端