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

相关推荐
夕颜11116 分钟前
如何让 AI 按照你的预期输出
后端
q***563825 分钟前
Spring Boot--@PathVariable、@RequestParam、@RequestBody
java·spring boot·后端
FREE技术1 小时前
学生成绩管理系统 基于java+springboot+vue实现前后端分离项目并附带万字文档(源码+数据库+万字详设文档+软件包+安装教程)
java·vue.js·spring boot·mysql
q***57501 小时前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端
猪猪拆迁队2 小时前
前端图形引擎架构设计:双引擎架构设计
前端·后端·架构
百***07182 小时前
IDEA+Docker一键部署项目SpringBoot项目
spring boot·docker·intellij-idea
GISer_Jing3 小时前
Node.js 开发实战:从入门到精通
javascript·后端·node.js
q***51893 小时前
Spring Boot 条件注解:@ConditionalOnProperty 完全解析
java·spring boot·后端
码事漫谈3 小时前
C/C++混合项目中的头文件管理:.h与.hpp的分工与协作
后端
码事漫谈3 小时前
C++中有双向映射数据结构吗?Key和Value能否双向查找?
后端