Jersey (JAX-RS) download binary file example

We learned about uploading binary file(s) in earlier blog posts. In this tutorial we will see, how to download binary file in Jersey (JAX-RS) application.

Very often HTTP API need to return binary responses. For e.g. we give user ability to download report in pdf or excel format. Based on user specific information, API resource method generate pdf file on server. With the help of this tutorial, you will learn how to send binary file, which is already generated or available as HTTP API responses.

Jersey Binaries Download Tutorial

This is a part of Jersey (JAX-RS) Restful Web Services Development Guides series. Please read Jersey + Spring Boot getting started guide.

1. Sample binary files

We have kept 4 sample binary files for our tutorial in /src/main/resources/static/ folder:

  1. sample.pdf
  2. sample.doc
  3. sample.jpg
  4. sample.png

2. Download binary file example resource file

File: /src/main/java/in/geekmj/resource/FileDownloadResource.java

package in.geekmj.resource;

import java.io.File;
import java.io.IOException;

import javax.activation.MimetypesFileTypeMap;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

/**
 * @author geekmj 
 * 
 * File download example
 */
@Path("/download")
@Component
public class FileDownloadResource {

	@Autowired
	private ResourceLoader resourceLoader;
	
	
	@Path("/any-file-type/{type}")
	@GET
	public Response anyFileType(@PathParam("type") String fileType) {

		/*
		 * We are loading file kept in resources/static/ folder using Spring
		 * ResourceLoader classpath mechanism. 
		 * We have following files: 
		 * 1. sample.doc 2. sample.jpg 3. sample.pdf 4. sample.png 
		 * Based on type passed, we load sample.<type> from resources folder. 
		 * We are using Spring ResourceLoader to load file.
		 */
		File file = null;
		String mimeType;
		try {

			file = resourceLoader.getResource("classpath:static/sample." + fileType).getFile();

			/*
			 * We can also use normal File constructor to load a file. 
			 * For e.g. File file = new File("C:\sample.pdf");
			 */

			if (!file.exists()) {
				throw new WebApplicationException(404);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		
		/* Finding MIME type for explicitly setting MIME */
		mimeType = new MimetypesFileTypeMap().getContentType(file);
		
		ResponseBuilder rb = Response.ok(file, mimeType);

		/* Setting file name and making sure file download instead of showing in browser */
		rb.header("Content-Disposition", "inline; filename=sample." + fileType);

		return rb.build();
	}
	
	/* Setting MIME type explicitly using @Produces annotation. 
	 * Content will displayed in browser if possible. */
	@Path("/png-file/")
	@GET
	@Produces("image/png")
	public Response pngFileType() {
		File file = null;
		try {

			file = resourceLoader.getResource("classpath:static/sample.png").getFile();
			
			if (!file.exists()) {
				throw new WebApplicationException(404);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		
		ResponseBuilder rb = Response.ok(file);

		/* Setting file name */
		rb.header("Content-Disposition", "attachment; filename=sample.png");

		return rb.build();
	}

}

2.1 Method anyFileType

Method anyFileType handle API URI  /download/any-file-type/<fileType>. When we access API with Valid fileType values (pdf, jpg, doc and png), it respond with sample file of that type.

Response header Content-Disposition value inline make sure file displayed in browser, where it is possible.

We have not used @Produce annotation to specify MIME type. We have specified MIME type dynamically using following code.

mimeType = new MimetypesFileTypeMap().getContentType(file);

ResponseBuilder rb = Response.ok(file, mimeType);

2.2 Method pngFileType

This method will handle /download/png-file/ API URI.

Response MIME type specified using @Produce annotation. sample.png file saved or prompt to saved on drive. It enabled using Response header Content-Disposition value attachment.

You can test this API by accessing http://localhost:8080/download/png-file.

References

  1. MIME type
  2. Jersey Tutorial
Download Icon SmallDownload the Full ProjectGithub IconFollow Project On Github

Leave a Reply

Your email address will not be published. Required fields are marked *