When developing back-end programs, we often need to implement REST APIs so that the front-end (such as Angular, React) can download files. It is easy to implement file downloading REST APIs with Spring Boot StreamingResponseBody
.
As the follow code shows, we only need to copy the file’s InputStream
to StreamingResponseBody.OutputStream
with FileCopyUtils.copy()
.
import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; @RestController @RequestMapping("/logs") public class LogController { @GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE) public ResponseEntity<StreamingResponseBody> downloadLog() throws FileNotFoundException { InputStream inputStream = new FileInputStream("/path/to/log"); StreamingResponseBody body = outputStream -> FileCopyUtils.copy(inputStream, outputStream); return ResponseEntity.ok() .header("Content-Disposition", "attachment;filename=server.log") .body(body); } }
Now, you open http://localhost:8080/logs/download with your browser, and the file will be downloaded directly!