Table of contents
1.
Introduction
2.
JAX-RS file upload
3.
Frequently Asked Questions
3.1.
What are the key features of JAX-RS API?
3.2.
What are the request method designator annotations in JAX-RS API?
3.3.
What is Jersey?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

JAX-RS File Upload

Author Yashesvinee V
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JAX-RS or Java API for RESTful Web Services is a Java API used to create web services. JAX-RS, like JAX-WS, uses annotations to simplify the development and deployment of web services. Jersey is an implementation of JAX-RS API but is not part of standard JDK. Hence, we have to include all the required jars to use Jersey. We shall see an example of a JAX-RS file upload using Jersey.

JAX-RS File Upload

JAX-RS file upload

To upload a file using JAX-RS API with Jersy implementation, we require the Jersey jar files. Download them from here.

We make use of two main annotations for this example.

  • The @FormDataParam("file") annotation takes a file as a parameter in the service class. 
     
  • The @Consumes(MediaType.MULTIPART_FORM_DATA) annotation provides MIME information about the uploaded file.
     
  • The @Path annotation defines the relative URI path for the RESTful resource.
     
  • The @POST annotation is a request method designator to process HTTP POST requests.
     

Here is the code to upload a file using the JAX-RS API.

package fileUploadService;  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import javax.ws.rs.Consumes;  
import javax.ws.rs.POST;  
import javax.ws.rs.Path;  
import javax.ws.rs.core.MediaType;  
import javax.ws.rs.core.Response;  
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;  
import org.glassfish.jersey.media.multipart.FormDataParam;  
@Path("/files")  
public class FileUpload {  
    @POST  
    @Path("/upload")  
    @Consumes(MediaType.MULTIPART_FORM_DATA)  
    public Response fileUpload(  
            @FormDataParam("file") InputStream uploadedInputStream,  
            @FormDataParam("file") FormDataContentDisposition detail) {  
            String fileLoc = "D://" + detail.getFileName();  
                    //saving file  
            try {  
                FileOutputStream fout = new FileOutputStream(new File(fileLoc));  
                int read = 0;  
                byte[] bytes = new byte[1024];  
                fout = new FileOutputStream(new File(fileLoc));  
                while ((read = uploadedInputStream.read(bytes)) != -1) {  
                    fout.write(bytes, 0, read);  
                }  
                fout.flush();  
                fout.close();  
            } catch (IOException e) {e.printStackTrace();}  
            String display = "The file has been uploaded to : " + fileLoc;  
            return Response.status(200).entity(display).build();  
        }  
  }  
You can also try this code with Online Java Compiler
Run Code

Following is the content of the web.xml file.

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
<servlet>  
    <servlet-name>Jersey REST Service</servlet-name>  
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>  
    <init-param>  
        <param-name>jersey.config.server.provider.packages</param-name>  
        <param-value>fileUploadService</param-value>  
    </init-param>  
    <init-param>  
    <param-name>jersey.config.server.provider.classnames</param-name>  
    <param-value>org.glassfish.jersey.filter.LoggingFilter;  
    org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>  
</init-param>  
    <load-on-startup>1</load-on-startup>  
  </servlet>  
  <servlet-mapping>  
    <servlet-name>Jersey REST Service</servlet-name>  
    <url-pattern>/rest/*</url-pattern>  
  </servlet-mapping>  
</web-app>   

Index.html

<!DOCTYPE HTML>
<html>
<body>
<h1>File Upload example with Jersey</h1>
 
<form action="rest/files/upload" method="post" enctype="multipart/form-data">  

Select a file: <input type="file" name="file" size="50" />
    <br/><br/>
  <input type="submit" value="Upload" />
</form>
 
</body>
</html>

Output:

Choose a file

File Upload example output

Click on Upload.

Select the file for Upload

The file is uploaded.

File uploaded

Frequently Asked Questions

What are the key features of JAX-RS API?

It is a POJO-based API that provides annotations and interfaces. It is also an HTTP-based API. It can be applied to a wide variety of HTTP entity-body content types. It is container-independent.

What are the request method designator annotations in JAX-RS API?

@GET, @PUT, @POST, @DELETE and @HEAD are the request method designator annotations in JAX-RS API that correspond to the HTTP request methods GET, PUT, POST, DELETE and HEAD.

What is Jersey?

Jersey is an open-source framework for developing RESTful web services with JAX-RS APIs. It is a JAX-RS reference implementation and provides its API to extend the JAX-RS toolkit with additional features and utilities.

Conclusion

This blog discusses an example of RESTful JAX-RS file upload capability using Jersey. Check out our articles on Types of web services, Java Web Services and SOAP API. Explore our Library on Coding Ninjas Studio to gain knowledge on Data Structures and Algorithms, Machine Learning, Deep Learning, Cloud Computing and many more! Test your coding skills by solving our test series and participating in the contests hosted on Coding Ninjas Studio! 

Looking for questions from tech giants like Amazon, Microsoft, Uber, etc.? Look at the problems, interview experiences, and interview bundle for placement preparations. Upvote our blogs if you find them insightful and engaging! Happy Coding!

Thank you

Live masterclass