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

相关推荐
zzb15805 小时前
RAG from Scratch-优化-query
java·数据库·人工智能·后端·spring·mybatis
必胜刻6 小时前
RESTful 基础:资源、路径与方法对应关系详解
后端·restful
XPoet7 小时前
AI 编程工程化:Hook——AI 每次操作前后的自动检查站
前端·后端·ai编程
J2虾虾7 小时前
在SpringBoot中使用Druid
java·spring boot·后端·druid
程序员小假7 小时前
为什么要有 time _wait 状态,服务端这个状态过多是什么原因?
java·后端
qwert10378 小时前
跨域问题解释及前后端解决方案(SpringBoot)
spring boot·后端·okhttp
90后的晨仔9 小时前
OpenClaw Windows 完整安装指南
后端
码喽7号9 小时前
springboot学习四:RESTful风格+swagger
spring boot·学习·restful
IT_陈寒10 小时前
Vue组件复用率提升300%?这5个高阶技巧让你的代码焕然一新!
前端·人工智能·后端
beata10 小时前
Spring Boot基础-2:Spring Boot 3.x 起步依赖(Starter)深度拆解:为什么引入一个依赖就够了?
spring boot·后端