Download text file from JAX-RS

In this tutorial we will discuss about download text files from JAX-RS,  for user to download a file, annotate the method with @Produces(“text/plain”) :

  1. Put @Produces(“text/plain”) on service method, with a Response return type. It means the output is a text file.
  2. Set “Content-Disposition” in Response header to tell browser pop up a download box for user to download.

1. Download File in JAX-RS

See a full example to download a text file in JAX-RS.

package com.dineshonjava.ws.rest;

import java.io.File;

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

/**
 * @author Dinesh Rajput
 *
 */
@Path("/salaryslipfile")
public class EmployeeSalarySlip {
 private static final String FILE_PATH = "d:salary.log";
  
 @GET
 @Path("/get")
 @Produces("text/plain")
 public Response getSalarySlipFile() {
 
  File file = new File(FILE_PATH);
 
  ResponseBuilder response = Response.ok((Object) file);
  response.header("Content-Disposition",
   "attachment; filename="salary_slip_file.log"");
  return response.build();
 
 }
 
}

2. Test

Deploy above JAX-RS service, access this URI pattern : “http://localhost:8181/sdnext/doj/salaryslipfile/get“.

Figure : Text file “d:salary.log” from server is prompt for user to download, with a new file name “salary_slip_file.log

Download text file from JAX-RS

Download SourceCode
Download text file from JAX-RS.zip

References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next