简体   繁体   中英

How to add the full path with file to the view?

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM