Skip to content
This repository has been archived by the owner on Jun 16, 2022. It is now read-only.

FileService Tutorial

Joshua Zenn edited this page Mar 15, 2022 · 5 revisions

For the most up to date information, please read the docs: https://cs4850group5a.github.io/VirtuDoc/com/virtudoc/web/service/FileService.html

Pre-requisites

This tutorial assumes that you already have a controller (FileController) and a Thymeleaf template (upload.html). It is assumed that you already have a GET route set up to render upload.html at the route (/upload). When implementing these features in Virtudoc, these files and classes should be renamed to something that better represents what your code does (e.g. VisitSummaryController).

Step 1: Create a form

In upload.html, add the following:

<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>

Source

Step 2: Add controller route

At the top of your FileController class, import the FileService:

@Autowired
private FileService fileService;

Then create the upload route:

@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultiPartFile file) {
  FileEntity uploadedFile = fileService.CreateFile(file);
  // TODO: Do additional processing on this file (if required).
  return "upload.html";
}

Note that this will create a file that is available to the public. To lock a file so that only the patient and their doctors can access the file, use FileEntity uploadedFile = fileService.CreateFile(file, activeUser); where activeUser is the currently logged-in user.

Step 3: File downloads

To allow for file downloads, create a new route in your controller.

@GetMapping("/download")
public void downloadFile(HttpServletResponse response) {
  FileEntity fileEntity = // TODO: Get file handle.
  FileCopyUtils.copy(fileService.GetFile(fileEntity), response.getOutputStream());
  response.flushBuffer();
}

To get the file handle, you can use a GET variable as shown here and pass through the file ID from somewhere else (e.g. a file listing page): https://stackoverflow.com/a/5673356. You could then call /download/5 to download the file with ID 5. Note that if you call fileService.GetFile() on a non-public file, you will need to pass a UserAccount object in a similar manner to fileService.CreateFile() as noted above.