RESTEasy – File Download Example

RESTEasy is JBOSS provided implementation of JAX-RS specification for building RESTful Web Services and RESTful Java applications. RESTEasy works in combination with HTTP media types for providing the response in specific formats such as images, pdf or text.

The core component to configure for enabling support for multiple media types in response is @Produces annotation. A full list of such media types can be found in this link.

For demonstration purpose, I will be showing example of downloading one image, one text and one pdf file. Similarly you can build for other media types (file types).

1) Create a maven project

mvn archetype:generate -DgroupId=com.howtodoinjava -DartifactId=RESTfulDemoApplication 
-DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

mvn eclipse:eclipse -Dwtpversion=2.0

2) Update jax-rs dependencies in pom.xml file

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.howtodoinjava</groupId>
  <artifactId>RESTfulDemoApplication</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>RESTfulDemoApplication Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <repositories>
   	<repository>
      <id>jboss</id>
      <url>http://repository.jboss.org/maven2</url>
   	</repository>
  </repositories>
  <dependencies>
    <!-- core library -->
	<dependency>
		<groupId>org.jboss.resteasy</groupId>
		 <artifactId>resteasy-jaxrs</artifactId>
		<version>2.3.1.GA</version>
	</dependency>
	<dependency>
		<groupId>net.sf.scannotation</groupId>
		<artifactId>scannotation</artifactId>
		<version>1.0.2</version>
	</dependency>
  </dependencies>
  <build>
    <finalName>RESTfulDemoApplication</finalName>
  </build>
</project>

3) Create service class and APIs with corresponding media types in @Produces annotation

package com.howtodoinjava.service;

import java.io.File;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

@Path("/file-management")
public class FileServer
{
	@GET
	@Path("/{fileName}/text")
	@Produces("text/plain")
	public Response getFileInTextFormat(@PathParam("fileName") String fileName) 
	{
		System.out.println("File requested is : " + fileName);
		
		//Put some validations here such as invalid file name or missing file name
		if(fileName == null || fileName.isEmpty())
		{
			ResponseBuilder response = Response.status(Status.BAD_REQUEST);
			return response.build();
		}
		
		//Prepare a file object with file to return
		File file = new File("c:/demoTxtFile.txt");
		
		ResponseBuilder response = Response.ok((Object) file);
		response.header("Content-Disposition", "attachment; filename="howtodoinjava.txt"");
		return response.build();
	}
	
	@GET
	@Path("/{fileName}/pdf")
	@Produces("application/pdf")
	public Response getFileInPDFFormat(@PathParam("fileName") String fileName) 
	{
		System.out.println("File requested is : " + fileName);
		
		//Put some validations here such as invalid file name or missing file name
		if(fileName == null || fileName.isEmpty())
		{
			ResponseBuilder response = Response.status(Status.BAD_REQUEST);
			return response.build();
		}
		
		//Prepare a file object with file to return
		File file = new File("c:/demoPDFFile.pdf");
		
		ResponseBuilder response = Response.ok((Object) file);
		response.header("Content-Disposition", "attachment; filename="howtodoinjava.pdf"");
		return response.build();
	}
	
	@GET
	@Path("/{fileName}/image")
	@Produces("image/jpeg")
	public Response getFileInJPEGFormat(@PathParam("fileName") String fileName) 
	{
		System.out.println("File requested is : " + fileName);
		
		//Put some validations here such as invalid file name or missing file name
		if(fileName == null || fileName.isEmpty())
		{
			ResponseBuilder response = Response.status(Status.BAD_REQUEST);
			return response.build();
		}
		
		//Prepare a file object with file to return
		File file = new File("c:/demoJpegFile.jpeg");
		
		ResponseBuilder response = Response.ok((Object) file);
		response.header("Content-Disposition", "attachment; filename="howtodoinjava.jpeg"");
		return response.build();
	}
}

4) Put files to be download in referenced locations

I am referencing files from “c:/<file>”. Copy files from distribution folder in download link, and paste them in c: before running this example.

5) Test the application

Below are snaps of download window appear in browser for requesting URLs:

http://localhost:8080/RESTfulDemoApplication/file-management/demoTxtFile/text

download_txt

http://localhost:8080/RESTfulDemoApplication/file-management/demoPDFFile/pdf

download_pdf
http://localhost:8080/RESTfulDemoApplication/file-management/demoJpegFile/image

download_image

 

If you want to download sourcecode of above example, follow below given link.

Source code download

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

10 thoughts on “RESTEasy – File Download Example”

  1. I can not make it download utf-8 file name correctly,
    Example my name “Nguyễn văn đức.doc”

    I will be replace some special characters

    Reply
  2. Very interessant .
    but if i would streaming the byte[] of a image that is saved into a db with jpa ? Into the record of jpa entity on dba is saved both the byte[] and mymetype. I can get many mymetypes into db ( jpg or bmp or gif or png).
    Another thing is that i would streaming the image for show into a webpage into a tag image with attribute src .
    I not would get as attachment but direct on webpage .

    Tank you for your attention .
    mauro

    Reply
  3. Hello,
    I am writing a pure Java client. Can you please provide a client side implementation example on how to call this service and get the file response?

    Thank you so much.

    Reply
  4. Short question: I need to solve very similar problem, but instead of the file itself, I need to return URL to the file in the response. So something like this (let’s assume XML response):

    Any idea how to do that?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.