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

相关推荐
oden1 小时前
0成本搭建!20分钟用 Workers AI + Vectorize 搞定 RAG(附全套源码)
后端
不会画画的画师2 小时前
Go开发指南:io/ioutil包应用和迁移指南
开发语言·后端·golang
JIngJaneIL2 小时前
基于java + vue个人博客系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
从心归零3 小时前
springboot-jpa的批量更新方法
java·spring boot·spring
tiancao2223 小时前
SpringBoot使用Camunda REST Client调用独立部署的Camunda7
spring boot·集成·独立服务器·rest api·camunda7
youliroam3 小时前
ESP32-S3+OV2640简单推流到GO服务
开发语言·后端·golang·esp32·ov2640
码luffyliu4 小时前
从 2 小时价格轮询任务通知丢失,拆解 Go Context 生命周期管控核心
后端·golang·go
a努力。4 小时前
宇树Java面试被问:方法区、元空间的区别和演进
java·后端·面试·宇树科技
码事漫谈4 小时前
二叉树中序遍历:递归与非递归实现详解
后端
码事漫谈4 小时前
跨越进程的对话之从管道到gRPC的通信技术演进
后端