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

相关推荐
canonical_entropy16 分钟前
可逆计算的方法论来源
后端·低代码
数据知道33 分钟前
【Flask】一文掌握 Flask 基础用法
数据库·后端·python·flask·python web
q***735535 分钟前
windows配置永久路由
android·前端·后端
Dandelion____z1 小时前
AI 驱动业务的致命风险:如何用架构设计守住安全底线?
java·大数据·人工智能·spring boot·aigc·jboltai
码事漫谈1 小时前
不懂汇编的后端不是一个好的开发
后端
码事漫谈1 小时前
AI时代,汇编语言还有必要学吗?我的惨痛教训与思考
后端
考虑考虑1 小时前
jpa将SQL记录到日志文件
spring boot·后端·spring
踏浪无痕2 小时前
准备手写Simple Raft(二): 跑通最基本的Leader选举
后端·raft
d***9352 小时前
【Spring】Cookie和Session是什么
java·后端·spring
kevinzeng2 小时前
MVC 和 DDD
后端·领域驱动设计