繁体   English   中英

如何使用resttemplate将多部分文件和某些字段传递给另一个api?

[英]How to pass multipart file and some fields to another api using resttemplate?

我想将多部分文件以及用户名和电子邮件地址传递给另一个控制器。 当我尝试时,出现错误“必需的请求不是多部分文件”。

其余模板代码:

    val headers = LinkedMultiValueMap<String, String>()
    headers["x-apikey"] = apiKey
    headers["content-type"] = "multipart/form-data"

    println("updateFileHeaderStatusByIdFlowUrl : " + uploadCsvFileFlowUrl)

    val body = LinkedMultiValueMap<String, Any>()
    body.add("multipartFile", multipartFile)
    body.add("backofficeUsername", backofficeUsername)
    body.add("backofficeUserEmailAddress", backofficeUserEmailAddress)

    val requestEntity = HttpEntity<LinkedMultiValueMap<String, Any>>(body, headers)


    var response = restTemplate.exchange("localhost:8080/uploadCSVFile",
            HttpMethod.POST, requestEntity, String::class.java)

    System.out.println("response status: " + response.getStatusCode())
    System.out.println("response body: " + response.getBody())

REST API:

     @PostMapping("/uploadCSVFile/")
     fun uploadCSVFile(@RequestParam multipartFile: MultipartFile,
                  @RequestParam backofficeUsername: String,
                  @RequestParam backofficeUserEmailAddress: String) {}

尝试在方法签名中添加multipart/form-data

@PostMapping("/uploadCSVFile/", consumes = { MediaType.MULTIPART_FORM_DATA })
         fun uploadCSVFile(@RequestParam multipartFile: MultipartFile,
                      @RequestParam backofficeUsername: String,
                      @RequestParam backofficeUserEmailAddress: String) {}

如果是标头,则在Java中添加以下内容。 setContentType()用于将Http媒体类型设置为服务器,在这种情况下,它应该是MultiPart。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM