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 天前
什么是开源?小白如何快速学会开源协作流程并参与项目
java·前端·后端·开源
Thomas游戏开发1 天前
Unity3D IL2CPP如何调用Burst
前端·后端·架构
货拉拉技术1 天前
货拉拉离线大数据迁移-验数篇
后端·架构
用户6802659051191 天前
如何利用 Endpoint Central 提高企业终端管理效率
javascript·后端·面试
廋到被风吹走1 天前
【Spring】Spring Context 详细介绍
java·后端·spring
风之子npu1 天前
AMBA AXI - transaction order记录
后端·restful
Clarence Liu1 天前
虚拟机与容器的差异与取舍
linux·后端·容器
sheji34161 天前
【开题答辩全过程】以 山林湖泊生态文明建设管控系统为例,包含答辩的问题和答案
java·spring boot
幽络源小助理1 天前
SpringBoot兼职发布平台源码 | JavaWeb项目免费下载 – 幽络源
java·spring boot·后端
co松柏1 天前
AI+Excalidraw,用自然语言画手绘风格技术图
前端·人工智能·后端