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

相关推荐
itmigrate18 分钟前
Rust 里的所有权误区:不是不写 clone 就叫高性能
开发语言·后端·rust
码事漫谈24 分钟前
Deepseek v5 来了
后端
爱勇宝31 分钟前
你可能成不了技术大佬,然后呢?
前端·后端·程序员
JuiceFS37 分钟前
HeyGen:如何让全球 10+ GPU 集群训练不再等待数据?
人工智能·后端
暧暧内含光1 小时前
Electron 桌面应用打包原理与实战避坑
后端
郭小李1 小时前
spring @PathVariable 注解用法
java·后端·spring
jaysee-sjc1 小时前
【苍穹外卖】Day12:工作台数据看板与 Excel 报表导出
java·开发语言·数据库·spring boot·spring·微信·excel
乔旭伟1 小时前
从一次「报错但成功」查起:SQLAlchemy async 的对象过期与 commit 时机
后端
用户360055579002 小时前
Kestrel_VLLM - 22 · MoE FFN 位级镜像收口:整模型逐层 L2 全等达成
后端
前端小万2 小时前
想做个人副业别乱买服务器!我的 5 个月真实开销分享
前端·后端·github