REST API Download File using Jersey 2 – RESTful Web Services Tutorial

7 years ago Lalit Bhagtani 0

REST API Download File :- In this tutorial, we will learn to download a file with JAX-RS using Jersey 2.

Let’s try to understand it with an example.

Example 1 :-

In this example of rest api download file, we will hit this URL <base URL>/books/download/{ext}/{id} with HTTP GET method to download a book file. The value of @PathParam (“ext”) indicates the type of the file ( pdf, docx, txt), while the value of @PathParam(“id”) indicates the id of the book, which you want to download.

We will use APPLICATION_OCTET_STREAM MIME media type in @Produces annotation and “Content-Disposition”, “attachment; filename=<filename>” key-value in the header of the request.

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.MediaType;
import javax.ws.rs.core.Response;

@Path("books")
public class FileDownloadExample {

  @GET
  @Produces(MediaType.APPLICATION_OCTET_STREAM)
  @Path("/download/{ext}/{id}/")
  public Response downloadBook(@PathParam("ext") String ext, @PathParam("id") String bookId){
    File file = new File("C:/temp/book_"+bookId+"."+ext);
    return Response.status(200)
        	.entity(file)
		.header("Content-Disposition", "attachment; filename=" + file.getName())
		.build();
  }
	
}



Example 2 :-

In this example, we will be using StreamingOutput class for downloading the file, rest of the things are same as of Example 1.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
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.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

@Path("books")
public class FileDownloadExample {
	
  @GET
  @Produces(MediaType.APPLICATION_OCTET_STREAM)
  @Path("/download/{ext}/{id}/")
  public Response getAllBooks(@PathParam("ext") String ext, @PathParam("id") String bookId){
		
    StreamingOutput output = new StreamingOutput() {
		
      @Override
      public void write(OutputStream output) throws IOException, WebApplicationException {
				
        try {					
             File file = new File("C:/temp/book_"+bookId+"."+ext);
             BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

             BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(output));
                    
             String line = bufferedReader.readLine();
             while(line != null){
                bufferedWriter.write(bufferedReader.readLine());
                bufferedWriter.flush();
                line = bufferedReader.readLine();
             }
             bufferedReader.close();
             bufferedWriter.close();					
        } catch (Exception e) {
             throw new WebApplicationException("File not found");
        }
      }
    };
		
    return Response.status(200)
                   .entity(output)
                   .header("Content-Disposition", "attachment; filename=" + bookId+"."+ext)
                   .build();
  }
}




Result :-

REST API Download File

References :-

  1. @Produces Java Docs
  2. StreamingOutput Java Docs

That’s all for REST API Download File using Jersey 2. If you liked it, please share your thoughts in comments section and share it with others too.