【问题标题】:Spring Resttemplate : how to post file and common String data at the same timeSpring Resttemplate:如何同时发布文件和普通字符串数据
【发布时间】:2018-01-26 04:01:35
【问题描述】:

我遇到了一个上传文件的请求,使用 spring resttemplate 上传文件 使用 http 标头“multipart/form-data”,还需要发布一些其他正常参数。如何实现?

【问题讨论】:

    标签: spring-mvc resttemplate


    【解决方案1】:

    您可以在应用程序中使用以下代码同时拥有多部分文件和普通请求参数。

    • 用您自己的网址替换。
    • 根据您的正常参数替换参数和值。

      String url ="http://example.com"; String fileAbsPath ="absolute path of your file"; String fileName = new File(fileAbsPath).getName(); Files.readAllBytes(Paths.get(fileAbsPath)); MultiValueMap<String, Object> data = new LinkedMultiValueMap<String, Object>(); ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(Paths.get(fileAbsPath))) { @Override public String getFilename() { return fileName; } }; data.add("file", resource); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("file","application/pdf"); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url) .queryParam("param1", "value1") .queryParam("param2", "value2") HttpEntity<> entity = new HttpEntity<> (data, requestHeaders); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> result =restTemplate.exchange( builder.toUriString(), HttpMethod.POST, entity, String.class); System.out.println(result.getBody());

    【讨论】:

    • 我也有这个问题,我试过了,但我得到: 原因:org.apache.tomcat.util.http.fileupload.FileUploadException:请求被拒绝,因为没有找到多部分边界
    【解决方案2】:

    您可以使用此代码。

       HttpHeaders headers = getCASHeaders(MediaType.MULTIPART_FORM_DATA);
       LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
       params.add("fileField", new FileSystemResource(""));//get file resource
       params.add("stringfield", stringPayload);
       HttpEntity requestEntity = new HttpEntity<>(params, headers);
       ResponseEntity<CasAssetApiResponse> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
    

    这将发送带有两个参数的 post call,您可以根据自己的意愿添加更多。

    也请看看这个stackoverflow answer

    【讨论】:

    • 但是这样,'stringfield'的值是一个LinkedList,而不是一个String......,他们的api确实识别这个值......
    【解决方案3】:

    虽然我的代码没有任何转换,但我收到错误“无法转换为 java.lang.String”。

    【讨论】:

    • 这不是问题的答案。
    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 2017-10-30
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多