@GetMapping("/download/{id}") public ResponseEntity downloadFile(@PathVariable String id) { File file = getFileById(id); StreamingResponseBody responseBody = out -> { Files.copy(file.toPath(), out); }; return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"") .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(responseBody); } Use code with caution.
: Only allow downloads of specific file types (e.g., .pdf , .jpg ). Use an allowlist rather than a blocklist, as attackers often find ways around filters.
: This header is crucial; it tells the browser to treat the response as an "attachment" rather than trying to display it (like a PDF or image) in the browser window. java download file from server to client
Downloading files from a server to a client in Java can range from simple direct transfers to complex, high-performance streaming solutions. Depending on whether you are building a standalone desktop app or a modern web service, the tools and techniques you choose will significantly impact both performance and security.
import java.io.*; import java.net.URL; public class SimpleDownload { public static void download(String fileURL, String destination) throws IOException { try (BufferedInputStream in = new BufferedInputStream(new URL(fileURL).openStream()); FileOutputStream out = new FileOutputStream(destination)) { byte[] dataBuffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { out.write(dataBuffer, 0, bytesRead); } } } } Use code with caution. : This header is crucial; it tells the
import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; public class NIODownload { public static void downloadNIO(String url, String targetPath) throws Exception { try (InputStream in = new URL(url).openStream()) { Files.copy(in, Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING); } } } Use code with caution.
: Never trust a filename provided by a user. An attacker could use ../ in the path to access sensitive system files like /etc/passwd . Always normalize the path and check that it stays within your intended directory. import java
In modern web applications, you aren't just downloading a file; you are serving it to a browser client. Spring Boot simplifies this by using ResponseEntity and specific HTTP headers.