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

相关推荐
烂蜻蜓7 分钟前
Flask入门教程(九):模板渲染——用Jinja2构建动态页面
后端·python·flask
QQ_21696290969 分钟前
【源码编号:project93375】SpringBoot汽车维修管理信息系统:客户车辆、维修预约、工单派发、配件结算全流程实战
java·spring boot·后端·汽车·springboot·需求分析
xcl092526 分钟前
流浪宠物领养管理系统开发实战:从需求分析到落地的完整指南
java·spring boot·需求分析·宠物
2601_962063231 小时前
【Spring Boot】掌握 Spring 事务:隔离级别与传播机制解读与应用
spring boot·spring·adb
gis开发之家1 小时前
Spring Boot 4 深度解析,JdbcTemplate 实战——轻量级数据库操作方案
java·数据库·spring boot·后端
李昊哲小课2 小时前
Spring Boot 4 旅游主题实战教程 阶段二:Web 开发基础
前端·spring boot·旅游
2601_962063973 小时前
Spring Boot拦截器(Interceptor)详解
java·spring boot·后端
李昊哲小课3 小时前
SpringBoot4 云端咖啡站 阶段一:起步与基础
spring boot
明月_清风3 小时前
GitHub Actions 从入门到实战:一文搞懂 CI/CD 自动化
后端·ci/cd·github