Am new to Java and I am building a spring boot REST API resource to download zipped file based on the list of IDs being passed. The zipped file should contain ID records from db. Mysql database has got multiple records with unique IDs. So the resource i build should return a zip file with various ids passed as parameter.
For example:
Database table 'Message':
ID|message detail|timestamp|payload|config
1|Test message|2019-08-28 16:00:25.0003470| This is the test payload|subscriber1:test,subscriber2:test1
2|Test Message1|2019-08-20 12:46:40.0007520| This is the test payload1|subscriber001:test,subscriber002:test1
If i pass just 1 as ID, it should only download the file onto local machine and not zip.
If i pass 1 and 2 as parameter in the url, it should return the zip file with both records present.
Currently i have built a resource which will download all records from the db to my local. I cant work out how to get it to download when single ID is passed and ZIP when multiple IDs are passed.
Here is the code snippet:
Any help would be much appreciated. Thank you
@GetMapping("/file/save")
@CrossOrigin(origins = "*")
public ResponseEntity<byte[]> download() throws Exception {
List<messageEntity> messageRecord = messageRepository.findAll();
ObjectMapper objectMapper = new ObjectMapper();
String xml = objectMapper.writeValueAsString(messageRecord);
byte[] stringtobytes= xml.getBytes();
String fileName = "file.xml";
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentLength(stringtobytes.length);
respHeaders.setContentType(MediaType.TEXT_XML);
respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
return new ResponseEntity<byte[]>(stringtobytes, respHeaders, HttpStatus.OK);
}