Friday, April 27, 2012

File Download in JAX-RS

In JAX-RS, for user to download a file, annotate the method with @Produces("text/plain") :

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

Download File in JAX-RS :

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

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;

@Path("/file")
public class FileService {

private static final String FILE_PATH = "c:\\file.log";

@GET
@Path("/get")
@Produces("text/plain")
public Response getFile() {
File file = new File(FILE_PATH);

ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition","attachment; filename=\"file_from_server.log\"");
return response.build();
}
}



File Type :
txt : @Produces("text/plain")
image  : @Produces("image/png")
pdf : @Produces("application/pdf")
excel : @Produces("application/vnd.ms-excel")

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

No comments:

Post a Comment