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

相关推荐
小江的记录本1 分钟前
【Redis】Redis全方位知识体系(附《Redis常用命令速查表(完整版)》)
java·数据库·redis·后端·python·spring·缓存
颜酱16 分钟前
回溯算法实战练习(3)
javascript·后端·算法
zihao_tom1 小时前
Spring Boot(快速上手)
java·spring boot·后端
Bear on Toilet1 小时前
基于Deepseek(C++)的SSE协议流式响应实现方案
chrome·后端·deepseek接入
didiplus1 小时前
Python 入门第三课:让程序"开口说话":90% 新手都忽略的输入输出技巧
后端
明月_清风2 小时前
宿命的对决:深度对比 JavaScript 与 Python 的异步进化论
后端·python
明月_清风2 小时前
别再纠结 Conda 了!2026 年,uv 才是 Python 环境管理的唯一真神
后端·python
salipopl2 小时前
Spring 中的 @ExceptionHandler 注解详解与应用
java·后端·spring
jessecyj2 小时前
SpringBoot详解
java·spring boot·后端
爱吃的小肥羊2 小时前
刚刚!Claude最强大模型泄露,Anthropic紧急封锁
后端