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

相关推荐
苏三说技术5 分钟前
Spring AI 2.1 正式发布 ,新增一个重要功能
后端
雪芽蓝域zzs35 分钟前
第14章:SpringBoot3 + MyBatis‑Plus 基础 CRUD(无 Redis)
spring boot
Rain的Java大神之路2 小时前
Spring AI 2.0 GA 深度复盘:Java 后端做 AI 的分水岭,到底画在哪?
java·后端·aigc
青石路2 小时前
不依赖 Spring,你会如何自实现 RabbitMQ 消息的消费(二)
后端·rabbitmq
Csvn3 小时前
Nginx 可观测性与工程化:指标、告警与发布回滚演练
后端·nginx
光泽雨3 小时前
IActionResult 是 ASP.NET Core Web API 中非常常用的一种控制器方法返回类型
后端·asp.net
唐老板4 小时前
前端和后端,转 AI 全栈怎么转
前端·后端
掘金安东尼4 小时前
中国移动 OAS 是什么:智能体开放服务空间、四项能力与「自研」说法的核实
人工智能·后端
JuiceFS4 小时前
缓存命中率 99.96%,小文件数量减少 99.92%:启智机器人 JuiceFS 生产实践
人工智能·后端·机器人
程序员鱼皮5 小时前
Antigravity 保姆级实战教程,从 0 到 1 万字干货!
前端·后端·ai编程