How to download file using java restful web services?
You need to do two stpes to download a file from java restful web services.
1) Annotate your service method with @Produces annotation. This annotation should have the file MIME type as a value. For example, if you are
downloading pdf file then MIME type should be "application/pdf", incase if you are downloading png image file, then MIME type should be
"image/png".
2) In the Response header, set “Content-Disposition” details, which helps to prompt download box on browser.
In the previous examples we have given details of application setup, dependencies, web.xml file configurations: If you want to
know about these configuration, please refer these:
Restful web services using RESTEasy hello world example.
Restful web services using Jersey hello world example.
Here is the service class to download file:
package com.java2novice.restful;
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("/download")
public class RestDownloadService {
@GET
@Path("/service-record")
@Produces("application/pdf")
public Response getFile() {
File file = new File("C:\java2novice\employee_1415.pdf");
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename=\"employee_1415.pdf\"");
return response.build();
}
}
|
Try below URL to download file:
http://localhost:8080/RestfulWebServices/download/service-record
|