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

相关推荐
间彧4 分钟前
面向切面编程(AOP)中的“通知”和 专门用于增强 Spring MVC 中控制器(Controller)的“通知”
后端
逻极8 分钟前
Rust数据类型(下):复合类型详解
开发语言·后端·rust
星释8 分钟前
Rust 练习册 12:所有权系统
开发语言·后端·rust
间彧8 分钟前
AOP中的五种通知类型在实际项目中如何选择?举例说明各自的典型应用场景
后端
间彧10 分钟前
Spring Boot中很多Advice后缀的注解和类,都是干什么的
后端
披着羊皮不是狼30 分钟前
Spring Boot——从零开始写一个接口:项目构建 + 分层实战
java·spring boot·后端·分层
Tony Bai1 小时前
Go GUI 开发的“绝境”与“破局”:2025 年现状与展望
开发语言·后端·golang
Tony Bai1 小时前
【Go模块构建与依赖管理】08 深入 Go Module Proxy 协议
开发语言·后端·golang
码事漫谈2 小时前
从一个问题深入解析C++字符串处理中的栈损坏
后端
码事漫谈2 小时前
C++ 核心基石:深入理解 RAII 思想,告别资源泄露的噩梦
后端