First, convert your List<String>
to the text you want client to receive:
StringBuilder buf = new StringBuilder();
for (String username : usernames)
buf.append(username).append("\r\n"); // or just "\n", your choice
String text = buf.toString();
Next, simply tell Spring that return value from method is the response itself, not a view name, by annotating method with @ResponseBody
.
A String
is automatically sent as text/plain
.
@PostMapping("/download")
@ResponseBody
public String handleFileUpload(RedirectAttributes redirectAttributes) throws Exception {
Database db = new Database();
List<String> usernames = db.getUsernames();
StringBuilder buf = new StringBuilder();
for (String username : usernames)
buf.append(username).append("\r\n"); // or just "\n", your choice
return buf.toString();
}
UPDATE
To cause the returned text to pop-up the file download dialog, you need to set the Content-Disposition
header.
To do that, you need to change return type to ResponseEntity<String>
and then set the header values like this:
@GetMapping("/download")
public ResponseEntity<String> handleDownload() throws Exception {
Database db = new Database();
List<String> usernames = db.getUsernames();
StringBuilder buf = new StringBuilder();
for (String username : usernames)
buf.append(username).append("\r\n"); // or just "\n", your choice
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=\"usernames.txt\"")
.contentType(MediaType.TEXT_PLAIN)
.body(buf.toString());
}