Spring Rest Template的多部分文件http请求到达时没有文件

时间:2018-10-31 14:22:21

标签: java spring httprequest messaging resttemplate

我有这个客户端,用于使用Rest Template发送多部分文件http请求

    @Component
    public class RestTemplatePost {

        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }

        @PostConstruct
        public void prepareMessage() throws Exception {

            File file = new File("****");
            File file2 = new File("****");

            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

            MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();


            form.add("files", file);
            form.add("files", file2);
            form.add("usertoken", "test");
            form.add("sendTo", "test);
            form.add("subject", "test");
            form.add("content", "test");

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(form, httpHeaders);

            String serverUrl = "http://localhost:8080/api/mails/send";

            List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<>();
            httpMessageConverters.add(new FormHttpMessageConverter());
            httpMessageConverters.add(new MappingJackson2HttpMessageConverter());

            restTemplate().setMessageConverters(httpMessageConverters);


            restTemplate().postForEntity(serverUrl, requestEntity, String.class);


        }
}

然后我在服务器端应收到请求:

@RestController
@RequestMapping("/api")
public class MainConroller {

    private static final Logger log = LoggerFactory.getLogger(MainConroller.class);
    @Autowired
    private MainService mainService;

    public MainConroller(MainService mainService) {
        this.mainService = mainService;
    }

    @PostMapping("/mails/send")
    public  void send(
            @RequestParam("usertoken") String usertoken,
            @RequestParam("sendTo") String sendTo,
            @RequestParam("subject") String subject,
            @RequestParam("content") String content,
            @RequestParam(required = false, name = "files") List<MultipartFile> multipartFiles) {
        log.debug("{}, {}, {}, {}", usertoken, sendTo, subject, content);

        mainService.processMessage(usertoken, sendTo, subject, content, multipartFiles);

    }
}

当我从客户端发送此请求时,除文件外,所有内容均到达服务器端。

收到请求后,RequestParam文件为空。

更新 消息转换器已按照建议明确删除,没有任何更改。

1 个答案:

答案 0 :(得分:0)

没有文件发送,因为没有HttpMessageConverter能够转换java.io.File。 另一方面,有一个ResourceHttpMessageConverter可以转换各种Resource,包括FileSystemResource

在创建FormHttpMessageConverter时默认添加PS RestTemplate,并且FormHttpMessageConverter也在后台使用。