Downloading file using Jersey

Very often, your application requires having a resource that allows users to download a file. This could be an endpoint where a user downloads some Report, their user data, or any other type of file.
To achieve this goal, you use StreamingOutput to copy the content of the file, and then add the stream to your Response object.

@GET
@Path("/download")
public Response download()
{
	String filename = "//someFolder/some-File.pdf"
	File file = new File(filename);
	final String newFileName = file.getName();
	StreamingOutput fileStream = output ->
	{
		try
		{
			java.nio.file.Path path = Paths.get(filename);
			byte[] data = Files.readAllBytes(path);
			output.write(data);
			output.flush();
		}
		catch (Exception e)
		{
			throw new WebApplicationException("File Not Found !!");
		}
	};
	return Response
			.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
			.header("content-disposition", "attachment; filename = " + newFileName)
			.build();
}