Fix Download File Controller Spring Boot -
download a file from Spring boot rest service - Stack Overflow
If you are dealing with multi-gigabyte files, use the StreamingResponseBody interface to write directly to the HttpServletResponse output stream.
: The best choice for very large files to prevent OutOfMemoryError by streaming the data directly to the response output stream. 4. Handling Large Files with StreamingResponseBody download file controller spring boot
: Optional but helpful for the browser to show a progress bar. 3. Alternative Implementation Strategies
@RestController @RequestMapping("/api/files") public class FileController { private final Path fileStorageLocation = Paths.get("uploads").toAbsolutePath().normalize(); @GetMapping("/download/{fileName:.+}") public ResponseEntity downloadFile(@PathVariable String fileName, HttpServletRequest request) { try { Path filePath = this.fileStorageLocation.resolve(fileName).normalize(); Resource resource = new UrlResource(filePath.toUri()); if (resource.exists()) { // Try to determine file's content type String contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath()); if (contentType == null) { contentType = "application/octet-stream"; } return ResponseEntity.ok() .contentType(MediaType.parseMediaType(contentType)) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } else { return ResponseEntity.notFound().build(); } } catch (MalformedURLException ex) { return ResponseEntity.badRequest().build(); } catch (IOException ex) { return ResponseEntity.internalServerError().build(); } } } Use code with caution. 2. Key Components of a File Download Response download a file from Spring boot rest service
: Ideal for files generated on-the-fly (like dynamic PDFs or CSVs).
: Efficient for streaming data without loading the entire file into memory. Resource resource = new UrlResource(filePath.toUri())
: Best for files stored on the local server disk.