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

相关推荐
爱码猿11 分钟前
Springboot结合thymeleaf模板生成pdf文件
spring boot·后端·pdf
IT_陈寒19 分钟前
SpringBoot 3.2实战:5个性能优化技巧让你的应用提速50%
前端·人工智能·后端
上进小菜猪35 分钟前
基于 YOLOv8 的农作物叶片病害、叶片病斑精准识别项目 [目标检测完整源码]
后端
老毛肚1 小时前
Spring源码探究2.0
java·后端·spring
程序员鱼皮1 小时前
你的 IP 归属地,是咋被挖出来的?
前端·后端·计算机·程序员·互联网·编程经验
Coder_Boy_1 小时前
基于SpringAI的在线考试系统软件系统验收案例
人工智能·spring boot·软件工程·devops
fisher_sky1 小时前
流媒体服务mediamtx和FFMpeg工具链联合实验
后端
qq_12498707532 小时前
基于SSM框架的智能密室逃脱信息管理系统(源码+论文+部署+安装)
java·大数据·人工智能·spring boot·后端·毕业设计·计算机毕业设计
掉鱼的猫2 小时前
从 Chat 到 Agent:Solon AI 带你进入“行动派”大模型时代
后端
vivo互联网技术2 小时前
vivo 微服务架构实践之 Dubbo 性能优化
java·后端·微服务·中间件·dubbo