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

相关推荐
道可到3 分钟前
国内最难入职的 IT 公司排行:你敢挑战哪一家?
前端·后端·面试
缓存征服者14 分钟前
使用周期性线程池实现流量平滑,我将Redis并发从300+降到1
后端
深圳蔓延科技14 分钟前
单点登录到底是什么?
java·后端
道可到15 分钟前
程序员养生十大违章:你中了几条?
前端·后端·面试
SimonKing16 分钟前
除了 ${},Thymeleaf 的这些用法让你直呼内行
java·后端·程序员
间彧21 分钟前
Java拦截器与过滤器的区别及生命周期分析
后端
XXX-X-XXJ26 分钟前
二:RAG 的 “语义密码”:向量、嵌入模型与 Milvus 向量数据库实操
人工智能·git·后端·python·django·milvus
科兴第一吴彦祖36 分钟前
基于Spring Boot + Vue 3的乡村振兴综合服务平台
java·vue.js·人工智能·spring boot·推荐算法
努力的白熊嗨1 小时前
多台服务器文件共享存储
服务器·后端
调试人生的显微镜1 小时前
CSS开发工具推荐与实战经验,让样式开发更高效、更精准
后端