assaf.gov
assaf.gov

Reputation: 527

How to send file in JAVA via POST without saving it to disk

I need to send file to a POST service from the server side code. The content of the file I need to send is in String format. I don't want to create the file in the disk. I can't find the way to send file without creating it in the disk.

I prefer not to create a TEMP file but this is what I managed to do.

How do I send file without saving it to disk, not even as TEMP file?

This is the code:

    String fileContent = generateFile();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    headers.add("apikey","myapikey");

    File tmpFile = File.createTempFile("test", ".tmp");
    FileWriter writer = new FileWriter(tmpFile);
    writer.write(fileContent);
    writer.close();

    BufferedReader reader = new BufferedReader(new FileReader(tmpFile));
    reader.close();

    FileSystemResource fsr = new FileSystemResource(tmpFile);

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

    HttpEntity<MultiValueMap<String, Object>> requestEntity
            = new HttpEntity<>(body, headers);

    String serverUrl = "https://api.com/api";

    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate
            .postForEntity(serverUrl, requestEntity, String.class);

    return response.getBody();

POSTMAN screenshot that I use to test the API and it works perfect

POSTMAN Body

POSTMAN Headers

Upvotes: 4

Views: 3837

Answers (1)

T A
T A

Reputation: 1756

Use a ByteArrayResource instead:

String fileContent = generateFile();
ByteArrayResource bar = new ByteArrayResource(fileContent.getBytes());

This way you will not have to create any resource on disk but keep it in memory instead.

Upvotes: 2

Related Questions