6

My use case:

  1. On user request create tmp file (I don't really need to create real file, but I need to have java.io.File instance)
  2. Process this file
  3. Return file and other meta data as json
  4. Remove tmp file permanently

My code looks like:

@GetMapping(produces = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<MultiValueMap<String, Object>> regeneratePdfTest() throws IOException {
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    File tempFile = File.createTempFile("temp-file-name", ".tmp");

    processFile(tempFile);

    parts.add("file", new HttpEntity<>(new FileSystemResource(tempFile)));
    parts.add("meta-data", new HttpEntity<>(someObject));

    return new ResponseEntity<>(parts, HttpStatus.OK);
}

(Is this code the best for this case?)

I aware about File.deleteOnExit(), but documentation said

Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification

In my case, I want delete file immediately after response (file have some private information and I don't want keep them, also safe memory as I don't need this file anymore).

File size can be very large (more than 200MB).

Update 1: If error happen I'd like delete file too.

Andrew Sasha
  • 1,254
  • 1
  • 11
  • 21
  • Why do you need to create the file. Can't you just write, whatever `processFile(tempFile)` does to file, directly into response? – tsolakp Nov 24 '17 at 18:08
  • I shout take original file, make few changes and output it to user. To make this changes I need to have `java.io.File` so I decided: take original file, make a copy, change copy, output copy, remove copy - it's not really what I need but very similar. I cann't make list of `tmp` files and reuse them, after request I have to remove this `tmp` permanently. – Andrew Sasha Nov 24 '17 at 18:30
  • Btw. how can I output to HttpEntity? – Andrew Sasha Nov 24 '17 at 18:33
  • There are many ways to do this without actual File. See for example this: https://stackoverflow.com/questions/5673260/downloading-a-file-from-spring-controllers. Why cant you read the original file make the changes in memory and write into response? Is it too big or you need to run special file commands against it? – tsolakp Nov 24 '17 at 19:48

0 Answers0