springBoot 实现文件提交(form表单提交)

Springboot 中使用 RestTemplate 向另一个RESTful api 请求multipart file方式如下:

@RequestMapping("/upload")
    public String postData(HttpServletResponse response, HttpServletRequest request) throws IOException, AWTException {
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");// 允许服务器向浏览器跨域响应时更改浏览器(客户端)的cookie
        String url = "http://file-center.vaiwan.com/file/uploadFile";
        MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
        File image = new File(filePath);
        bodyMap.add("file", new FileSystemResource(image));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> res = restTemplate.exchange(url,
                HttpMethod.POST, requestEntity, String.class);
        return res.getBody();
    }
上一篇:计算机网络学习(6)—— MQTT协议


下一篇:Springboot项目 RestTemplate+httpclient实现文件的上传和下载