Home  >  Web Services

Download File Using RESTful Web Services with JAX-RS

By Arvind Rai, November 19, 2013
On this page we will run the demo for how to download a file using RESTful Web Services with JAX-RS using Jersey. JAX-RS provides Response class that handles the downloading of file. Response.ok() method returns ResponseBuilder which is the class of JAX-RS core API. It accepts header arguments. Here we will discuss complete example using Jersey.
FileResource.java
package com.concretepage.rest;
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;
import javax.ws.rs.core.Response.ResponseBuilder;
@Path("/restwb") 
public class FileResource {
	@GET
	@Path("/download/{fname}/{ext}")
        @Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response  downloadFile(@PathParam("fname") String fileName,@PathParam("ext") String fileExt){
		File file = new File("C:/temp/"+fileName+"."+fileExt);
		ResponseBuilder rb = Response.ok(file);
		rb.header("Content-Disposition", "attachment; filename=" + file.getName());
		Response response = rb.build();
		return response;
	}
} 



web.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
	<display-name>JAX RS Application</display-name>
	<servlet>
	  <servlet-name>REST Service</servlet-name>
	<servlet-class>
	  com.sun.jersey.spi.container.servlet.ServletContainer
	</servlet-class>
	  <init-param>
	    <param-name>com.sun.jersey.config.property.packages</param-name>
	    <param-value>com.concretepage.rest</param-value>
	  </init-param>
	  <load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
	  <servlet-name>REST Service</servlet-name>
	  <url-pattern>/*</url-pattern>
	</servlet-mapping>
</web-app> 
Jersey JAR Dependencies in pom.xml
<dependencies>
	<dependency>
		<groupId>javax.ws.rs</groupId>
		<artifactId>jsr311-api</artifactId>
		<version>1.1.1</version>
   </dependency>
   <dependency>
		<groupId>com.sun.jersey</groupId>
		<artifactId>jersey-server</artifactId>
		<version>1.8</version>
	</dependency>           
</dependencies> 
To test the download of file, you need to put a file in a desired location and provide root path in FileResource.java. Now our download needs two parameter filename and extension. If we have a file as below

C:\temp\pdffile.pdf

Then our download URL will be

http://localhost:8080/RestWB/restwb/download/pdffile/pdf

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2020 concretepage.com | Privacy Policy | Contact Us