为什么无法使用RestTemplate将文件发送或发布到服务器?

问题描述 投票:0回答:1
    File fileJson = new File("answer.json");
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
    **body.add("answer", fileJson);**
    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
    String urlFinal = "url";
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.postForEntity(urlFinal, requestEntity, String.class);
    System.out.println(response);

服务器返回400错误,提示文件未在正文中发送。我想知道问题出在我的代码还是服务器。

该文件是JSON,必须以Multipart-Form-data发送。

作为示例,我只给urlFinal字符串加上了“ url”,但是有一个有效的url,因为我已经做过测试。

java spring file resttemplate
1个回答
0
投票

您需要将文件名和BAOS添加到MultiValueMap正文中,添加此:

File fileJson = new File("answer.json");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("filename", fileJson.getName());
body.add("file", new ByteArrayResource(Files.readAllBytes(fileJson.toPath()));
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
String urlFinal = "url";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(urlFinal, requestEntity, String.class);
System.out.println(response);

但不是最好的模式,因为您可以使用此方法更改代码:

@Service
public class FileUploadService {

    private RestTemplate restTemplate;

    @Autowired
    public FileUploadService(RestTemplateBuilder builder) {
        this.restTemplate = builder.build();
    }

    public void postFile(String filename, byte[] someByteArray) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // This nested HttpEntiy is important to create the correct
        // Content-Disposition entry with metadata "name" and "filename"
        MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
        ContentDisposition contentDisposition = ContentDisposition
                .builder("form-data")
                .name("file")
                .filename(filename)
                .build();
        fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
        HttpEntity<byte[]> fileEntity = new HttpEntity<>(someByteArray, fileMap);

        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", fileEntity);

        HttpEntity<MultiValueMap<String, Object>> requestEntity =
                new HttpEntity<>(body, headers);
        try {
            ResponseEntity<String> response = restTemplate.exchange(
                    "/urlToPostTo",
                    HttpMethod.POST,
                    requestEntity,
                    String.class);
        } catch (HttpClientErrorException e) {
            e.printStackTrace();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.