Spring Boot 使用 RestTemplate 调用文件上传接口

使用RestTemplate调用文件上传接口比较简单,和平时的用法差不多,只是需要注意的是

  1. 设置请求头 multipart/form-data
  2. 请求体使用 LinkedMultiValueMap 包装文件

具体参考 Test代码中的 upload方法实现

controller代码

@RestController
@RequestMapping("test")
public class TestController {

    @PostMapping("upload")
    public String upload(MultipartFile file) {
        return file.getOriginalFilename();
    }
}
复制代码

test代码

public class FileUploadTest {

    @Test
    public void testUpload() {
        final String url = "http://localhost:8080/test/upload";
        String upload = upload(url, new File("C:\Users\w-chenguohao\Desktop\系统安装部署说明.md"));
        System.out.println(upload);
    }

    private String upload(String url ,File file) {

        RestTemplate restTemplate = new RestTemplate();

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        //设置请求体,注意是LinkedMultiValueMap
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", new FileSystemResource(file));

        //封装请求报文
        HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);

        return restTemplate.postForObject(url, files, String.class);
    }
}
复制代码

输出结果

> 系统安装部署说明.md
复制代码

猜你喜欢

转载自juejin.im/post/7039891760452993037
今日推荐