Jersey file download example – StreamingOutput

In this Jersey file download example, we will learn to write a Jersey rest api which will be able to stream or download file (e.g. PDF/Excel/Text files) to requesting client. I will be using class for building this JAX-RS API.

Table of Contents

1. REST API to stream file with StreamingOutput
2. Jersey file download demo
3. Maven dependencies
4. web.xml changes

1. REST API to stream file with StreamingOutput

Below is the source code for writing an streaming REST API using JAX-RS Jersey using StreamingOutput class.

package com.howtodoinjava.jersey;

import java.nio.file.Files;
import java.nio.file.Paths;


public class JerseyService 
	public Response downloadPdfFile()
		StreamingOutput fileStream =  new StreamingOutput() 
			public void write( output) throws IOException, WebApplicationException 
					java.nio.file.Path path = Paths.get("C:/temp/test.pdf");
					byte[] data = Files.readAllBytes(path);
				catch (Exception e) 
					throw new WebApplicationException("File Not Found !!");
		return Response
	            .ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
	            .header("content-disposition","attachment; filename = myfile.pdf")

2. Jersey file download demo

If you hit the URL, “http://localhost:8080/JerseyDemos/rest/download/pdf“, you will get below shown alert in your browser to download the file. The filename with which PDF file will be saved, will be what you set in Response.header() method.

Jersey file download example
Jersey file download example
Please make sure, you have a file present in path given in API code, otherwise you will error.

3. Maven dependencies

For quick reference, see below maven file I am using for this demo.

<project xmlns="" xmlns:xsi=""
			<name> Repository for Maven</name>
		<!-- JAX-RS -->
		<!-- Jersey 2.19 -->

4. web.xml changes

And also, refer web.xml file in case you are using jersey 2 configuration.

 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "" >
  <display-name>Archetype Created Web Application</display-name>

Drop me your questions related to java streaming file download example in comments section below.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

3 thoughts on “Jersey file download example – StreamingOutput”

  1. Thanks a lot for the example, was looking for it for long time. I guess Files.readAllBytes(path) is not memory efficient and we can use some BufferedReader.

  2. Hey,
    I need to consume a download service which when tested from postman download the file with right contents but when the same is done through Java, JS(UI), i get corrupted file.
    Can you please help on this.



Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.