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

相关推荐
Codebee25 分钟前
Qoder CLI 与 OneCode 平台深度整合技术实践:CLI委托驱动的开发范式革新
后端
码事漫谈31 分钟前
C++程序执行起点不是main:颠覆你认知的真相
后端
可观测性用观测云38 分钟前
玩转 Pipelines 之修正链路错误状态码
后端
码事漫谈40 分钟前
C++26:开启新纪元
后端
q***07141 小时前
Java实战:Spring Boot application.yml配置文件详解
java·网络·spring boot
龙卷风04051 小时前
深入理解Spring AI Alibaba多Agent系统:图结构驱动的智能协作
人工智能·后端
用户8356290780511 小时前
C# 高效生成 Word 表格:复杂表格创建实战指南
后端·c#
q***42821 小时前
SpringCloudGateWay
android·前端·后端
我是小妖怪,潇洒又自在2 小时前
springcloud alibaba搭建
后端·spring·spring cloud
l***74942 小时前
springboot与springcloud对应版本
java·spring boot·spring cloud