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

相关推荐
郑州光合科技余经理19 分钟前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
李慕婉学姐1 小时前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
掘金酱1 小时前
「寻找年味」 沸点活动|获奖名单公示🎊
前端·人工智能·后端
颜酱1 小时前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
QQ5110082852 小时前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
WeiXin_DZbishe2 小时前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
玹外之音2 小时前
Spring AI MCP 无状态服务器实战:构建AI智能用户管理系统
java·后端
what丶k2 小时前
Spring AI 多模态开发全解析:从入门到企业级落地
后端·spring·ai编程
ATCB2 小时前
零门槛!PythonAnywhere 免费部署全指南:不止 Django,这些项目都能搭(附主流平台对比)
后端·python·django
雨落Re2 小时前
从设计到开发,过年我用十天使用AI搭建了一个完整的博客系统
前端·后端