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

相关推荐
weixin_BYSJ19878 小时前
springboot3家政平台小程序--附源码00904
java·javascript·spring boot·python·django·flask·php
凤山老林9 小时前
SpringBoot 3 启用 spring.factories 后如何升级替换原有的 spring.factories ?
spring boot·后端·spring
吃饱了得干活9 小时前
JVM垃圾回收:从新生代到ZGC,从理论到调优
java·jvm·后端
Conan在掘金9 小时前
鸿蒙报错速查:arkts-no-func-expressions 禁用 function 表达式,用了就炸,根因 + 真解法
后端
geovindu9 小时前
python: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·python·算法·搜索算法
程序员清风9 小时前
AI不是万能的,大家要专注实践!
java·后端·面试
刘沅10 小时前
Redis的哨兵机制
后端·面试
AmazingEgg10 小时前
从 LIKE 到 Elasticsearch:博客搜索引擎可插拔改造全记录
后端
未秃头的程序猿10 小时前
MCP协议火了,但到底怎么用?我花了一个周末用Java接入了5个MCP Server
后端·ai编程·mcp
Cosolar10 小时前
Claude Opus 5 系统提示词被完整泄露,共 135027 字符、约 3.4 万 token
人工智能·后端·架构