CodesJava

Easy learning with example program codes

Jax-rs file download example


RESTful web services:

REST stands for REpresentational State Transfer. Unlike SOAP it is a web standards based architecture and not protocol. It uses HTTP protocol for data communication. REST provides the facility to represent a resource in various formats like text, JSON and XML.

Note: JSON is the most popular format.

Jax-rs file download jersey example

ImageService.java

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("/image")
public class ImageService {
 private static final String FILE_PATH = "D:\\java.jpg";
 
 @GET
 @Path("/get")
 @Produces("image/png")
 public Response getFile() {
	File file = new File(FILE_PATH);
	ResponseBuilder response = Response.ok((Object) file);
	response.header("Content-Disposition",
		"attachment; filename=image_from_server.png");
	return response.build();
 
 }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  <servlet>
  	<display-name>JAX-RS REST Servlet</display-name>
  	<servlet-name>JAX-RS REST Servlet</servlet-name>
  	<servlet-class>
  	 com.sun.jersey.spi.container.servlet.ServletContainer
  	</servlet-class>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>JAX-RS REST Servlet</servlet-name>
  	<url-pattern>/services/*</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

index.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>  
  <body>
     <a href="services/image/get">Download file.</a> 
  </body>
</html>

Output:

jax-rs example6.1
 
Click on “Download file” link.
jax-rs example6.2
 
Download this example.
 



Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki