java后端发送formdata数据上传文件


import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Test
    public void testUpload() throws Exception {
        String url = "http://xxx"; //上传的地址
        String filePath = "C:\\Users\\admin\\Desktop\\123.jpg";

        RestTemplate rest = new RestTemplate();
        FileSystemResource resource = new FileSystemResource(new File(filePath));
        MultiValueMap param = new LinkedMultiValueMap<>();
        param.add("headPicFile", resource); //相当于MultipartFile的名称
//        param.add("fileName", "test.jpg");

        String string = rest.postForObject(url, param, String.class);
        System.out.println(string);

        //rest.postForObject(url, param, String.class)也可以用下面的方法替换
//        HttpEntity> httpEntity = new HttpEntity>(param);
//        ResponseEntity responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);
//        System.out.println(responseEntity.getBody());
    }

转载自https://blog.csdn.net/mhmyqn/article/details/26395743

 

你可能感兴趣的:(Java)