I want to send the full track to view and display like http://localhost:8080/fileaName. Then I push this link and save file on my disk.
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("src/main/resources/temp/")
.path(fileName)
.toUriString();
model.addAttribute("fileDownloadUri", fileDownloadUri);
Now I can't see the link on the page
<span th:href="${fileDownloadUri}"></span>
CodePudding user response:
Not sure how your controller's end point looks like. But I would use the below Controller and View to show a direct download link to a file.
Controller:
@GetMapping("/downloadFile/{fileId}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileId) {
// Load file from your source
AppUserDocument appUserDocument = someDocumentStorageService.getFile(fileId);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(appUserDocument.getFileType()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" appUserDocument.getFileName() "\"")
.body(new ByteArrayResource(appUserDocument.getData()));
}
And then on the thymeleaf view I would provide a download link like below:
<td> <a class="btn btn-sm btn-primary" th:href="@{/downloadFile/{id}(id=${myfile.id})}">Download</a></td>
You can refer my github repo on above here:
https://github.com/ajkr195/springbootfileupldnldRESTDB
Or provide your full controller method reponsible for this. So that the SO folks can help you out.