4

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

7
  • 1
    I personally prefer to use byte data type for this kind of use cases. And parsing it to relevant data type in server and client side. Commented Nov 17, 2019 at 19:06
  • I'm not sure how this answers my question Commented Nov 18, 2019 at 5:45
  • @user1913615 After sending a file, do you want to prase? Commented Nov 18, 2019 at 6:32
  • I mean if you can handle server side (where you send the POST request), take byte array as an input and then convert it to required data type. Commented Nov 18, 2019 at 8:51
  • @Avijit Barua, no. Commented Nov 19, 2019 at 6:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.