HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Jersey / File Download

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 javax.ws.rs.core.StreamingOutput 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.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

@Path("/download")
public class JerseyService 
{
	@GET
	@Path("/pdf")
	public Response downloadPdfFile()
	{
		StreamingOutput fileStream =  new StreamingOutput() 
		{
			@Override
			public void write(java.io.OutputStream output) throws IOException, WebApplicationException 
			{
				try 
				{
					java.nio.file.Path path = Paths.get("C:/temp/test.pdf");
					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 = myfile.pdf")
	            .build();
	}
}

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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd;
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.howtodoinjava.jersey</groupId>
	<artifactId>JerseyDemos</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<repositories>
		<repository>
			<id>maven2-repository.java.net</id>
			<name>Java.net Repository for Maven</name>
			<url>http://download.java.net/maven/2/</url>
			<layout>default</layout>
		</repository>
	</repositories>
	<properties>
		<jersey2.version>2.19</jersey2.version>
		<jaxrs.version>2.0.1</jaxrs.version>
	</properties>
	<dependencies>
		<!-- JAX-RS -->
		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>javax.ws.rs-api</artifactId>
			<version>${jaxrs.version}</version>
		</dependency>
		<!-- Jersey 2.19 -->
		<dependency>
			<groupId>org.glassfish.jersey.containers</groupId>
			<artifactId>jersey-container-servlet</artifactId>
			<version>${jersey2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-server</artifactId>
			<version>${jersey2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.glassfish.jersey.core</groupId>
			<artifactId>jersey-client</artifactId>
			<version>${jersey2.version}</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>JerseyDemos</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

4. web.xml changes

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

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
 
<web-app>
 
  <display-name>Archetype Created Web Application</display-name>
   
  <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
             <param-name>jersey.config.server.provider.packages</param-name>
             <param-value>com.howtodoinjava.jersey</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
  
    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
     
</web-app>
Sourcecode Download

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

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Rishi

    March 22, 2020

    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.

    Thanks

  2. Md Farooq

    June 27, 2017

    very simple yet very effective post, Liked it.

Comments are closed on this article!

Search Tutorials

Jersey Tutorial

  • Jersey – Hello World
  • Jersey2 – Hello World
  • Jersey – quickstart-archetype
  • Jersey – Custom Logging
  • Jersey – Set Cookie
  • Jersey – File Download
  • Jersey – File Upload
  • Jersey – Multi-File Upload
  • Jersey – Exception Handling
  • Jersey – MOXy JSON
  • Jersey – JSONP
  • Jersey – Google Gson
  • Jersey – Security

Jersey Client

  • Jersey Client – Access REST APIs
  • Jersey Client – Authentication
  • Jersey Client – Set Cookie

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)