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

相关推荐
parafeeee2 小时前
程序人生-Hello’s P2P
数据库·后端·asp.net
bug攻城狮3 小时前
Spring Boot应用内存占用分析与优化
java·jvm·spring boot·后端
迪巴拉15253 小时前
基于Vue与Spring Boot+Open Cv的智慧校园考勤系统
前端·vue.js·spring boot
今天你TLE了吗3 小时前
JVM学习笔记:第八章——执行引擎
java·jvm·笔记·后端·学习
me8323 小时前
【Java】踩坑实录:Spring Boot + Nginx 本地部署404终极排查:从80端口被占用到配置生效全流程
java·spring boot·nginx
XPoet4 小时前
AI 编程工程化:Rule——给你的 AI 员工立规矩
前端·后端·ai编程
韩立学长4 小时前
基于Springboot校园志愿者服务平台77pz7812(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
Java基基5 小时前
Spring让Java慢了30倍,JIT、AOT等让Java比Python快13倍,比C慢17%
java·开发语言·后端·spring
qq_12498707535 小时前
基于SpringBoot微信小程序的智能在线预约挂号系统(源码+论文+部署+安装)
spring boot·后端·微信小程序·毕业设计·计算机毕设·毕业设计源码
小马爱打代码5 小时前
SpringBoot + 异地多活 + 消息回放:金融级数据一致性容灾架构设计与演练
spring boot·金融