restTemplate 上传文件

public void fileUpload(){
    String url = "上传文件的接口地址";

    File file = new File("D:/test/test.png");
    FileSystemResource resource = new FileSystemResource(file);

    MultiValueMap param= new LinkedMultiValueMap<>();
    param.add("file",resource);// 文件
    param.add("otherParam1","一些其他参数");
    param.add("otherParam2","一些其他参数");

    ParameterizedTypeReference resultType = new ParameterizedTypeReference(){};

    HttpHeaders httpHeaders = new HttpHeaders();
    MediaType mediaType = MediaType.parseMediaType("multipart/form-data;charset=UTF-8"); // 上传文件需要设置的类型
    httpHeaders.setContentType(mediaType);

    HttpEntity> request = new HttpEntity<>(param, httpHeaders);

    // 提交post请求
    String result = restTemplate.exchange(url, HttpMethod.POST, request, resultType);

    LOGGER.info("result:{}",result);

}

你可能感兴趣的:(java开发)