ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

SpringBoot RestTemplate 上传文件

2026/8/16 22:01:49 拓冰建站 浏览量
SpringBoot RestTemplate 上传文件

SpringBoot RestTemplate 上传文件

    @Testpublic 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);}

或者

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