Spring Boot Download(Stream) file example
July 19, 2023
Here is a example code to download file using spring boot.
package com.shorterpost.springexample.controller;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.File;
@Controller
public class DownloadController {
@GetMapping("/download")
public ResponseEntity download(@RequestParam String path)
{
File file = new File(path);
final FileSystemResource resource = new FileSystemResource(file);
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.contentLength(file.length())
.header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename="+file.getName())
.body(resource);
}
}