JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

How to upload file using Jersey restful web services?


In this page you will see an example for how to upload a file using Jersey API in restful web services.

In order to implement file upload feature, include jersey-multipart dependency in your pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
    			http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>RestfulWebServices</groupId>
	<artifactId>RestfulWebServices</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-server</artifactId>
			<version>1.17</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-servlet</artifactId>
			<version>1.17</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey.contribs</groupId>
			<artifactId>jersey-multipart</artifactId>
			<version>1.17</version>
		</dependency>
	</dependencies>
</project>

web.xml file reference:

<web-app id="WebApp_ID" version="2.4"
	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">
	    
    <servlet>
		<servlet-name>jersey-serlvet</servlet-name>
			<servlet-class>
                     com.sun.jersey.spi.container.servlet.ServletContainer
                </servlet-class>
		<init-param>
		     <param-name>jersey.config.server.provider.packages</param-name>
		     <param-value>com.java2novice.restful</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
  
    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

Here is the HTML upload form:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
				"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload File Example</title>
</head>
<body>
	<h1>Upload File</h1>
    <form action="rest/test/upload" method="post" enctype="multipart/form-data">
    	<p>Select a file : <input type="file" name="file"/></p>
		<input type="submit" value="Upload File" />
    </form>
</body>
</html>

Here is the upload service class, we are using @FormDataParam annotation to receive uploaded file and FormDataContentDisposition to receive file properties like name, header, etc.

package com.java2novice.restful;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("test")
public class RestUploadService {

	private static final String FOLDER_PATH = "C:\my_files\";
	
	@POST
	@Path("/upload")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Produces(MediaType.TEXT_PLAIN)
	public String uploadFile(@FormDataParam("file") InputStream fis,
					@FormDataParam("file") FormDataContentDisposition fdcd) {
 
		OutputStream outpuStream = null;
		String fileName = fdcd.getFileName();
		System.out.println("File Name: " + fdcd.getFileName());
		String filePath = FOLDER_PATH + fileName;
		
		try {
			int read = 0;
			byte[] bytes = new byte[1024];
			outpuStream = new FileOutputStream(new File(filePath));
			while ((read = fis.read(bytes)) != -1) {
				outpuStream.write(bytes, 0, read);
			}
			outpuStream.flush();
			outpuStream.close();
		} catch(IOException iox){
			iox.printStackTrace();
		} finally {
			if(outpuStream != null){
				try{outpuStream.close();} catch(Exception ex){}
			}
		}
		return "File Upload Successfully !!";
 	}
}

Try below URL to upload file:

http://localhost:8080/RestfulWebServices/index.html

User Upload Form

Output

<< Previous Program | Next Program >>

Restful Web Services Examples

  1. Restful web services using RESTEasy hello world example.
  2. Restful web services using Jersey hello world example.
  3. JAX-RS @Path annotation example
  4. JAX-RS @Path annotation with regular expression match example
  5. JAX-RS @PathParam annotation example
  6. JAX-RS @QueryParam and @DefaultValue annotations example
  7. JAX-RS @MatrixParam annotation example
  8. How to read multiple values of a query paramter in JAX-RS restful web services?
  9. How to pass header parameters as method inputs in JAX-RS restful web services?
  10. How to read header parameters in JAX-RS restful web services?
  11. JAX-RS @FormParam annotation example
  12. How to upload file using Jersey restful web services?
  13. How to download file using java restful web services?
  14. XML based Restful web service with RESTEasy and JAXB.
  15. XML based Restful web service with Jersey and JAXB.
  16. Json based Restful web service with RESTEasy, Jettison and JAXB
  17. Json based Restful web service with RESTEasy and Jackson
  18. Json based Restful web service with Jersey and Jackson
  19. How to input json request with Jersey and Jackson?
  20. Java client for restful web service using java.net package
  21. Java client for restful web service using Jersey API
  22. Java restful webservices with HTTP basic authentication.
Knowledge Centre
What is adapter class?
An adapter class provides the default implementation of all methods in an event listener interface. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface. You can define a new class by extending one of the adapter classes and implement only those events relevant to you.
Famous Quotations
Tomorrow is often the busiest day of the week.
-- Spanish Proverb

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2018 by Nataraja Gootooru. All Rights Reserved.