Loading...
Loading...
Loading...
Loading...

How to Jersey File Upload Example

View: 554    Dowload: 1   Comment: 0   Post by: hanhga   Category: Javascript   Fields: Other

Download  how-to-jersey-file-upload.rar (4.03 KB)

You need to Sign In to download the file how-to-jersey-file-upload.rar
If you do not have an account then Sign up for free here

In this Jersey tutorial, we will be learning to upload binary files(e.g. PDF files in this example) using Jersey’s multipart form data support. We will learn below required changes to complete the functionality.

Add Jersey maven multipart dependency

To use multipart features you need to add jersey-media-multipart module to your pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>2.19</version>
</dependency>

Add MultiPartFeature in web.xml

Further, you are required to add MultiPartFeature in Jersey configuration to let it know that you will use multipart requests. Simplest way is to add support through web.xml file.

<servlet>
    <servlet-name>jersey-serlvet</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.howtodoinjava.jersey</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Writing Upload REST API

Now look at actual REST API for file upload, which will receive and save the file.

@POST
@Path("/pdf")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadPdfFile(  @FormDataParam("file") InputStream fileInputStream,
                                @FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception
{
    String UPLOAD_PATH = "c:/temp/";
    try
    {
        int read = 0;
        byte[] bytes = new byte[1024];
 
        OutputStream out = new FileOutputStream(new File(UPLOAD_PATH + fileMetaData.getFileName()));
        while ((read = fileInputStream.read(bytes)) != -1) 
        {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e) 
    {
        throw new WebApplicationException("Error while uploading file. Please try again !!");
    }
    return Response.ok("Data uploaded successfully !!").build();
}

Test file upload using HTML Form

Simply create a file ‘fileUpload.html‘ file in ‘webapp‘ folder and paste this code.

<html>
    <body>
        <h1>File Upload Example - howtodoinjava.com</h1>
     
        <form action="rest/upload/pdf" method="post" enctype="multipart/form-data">
     
            <p>Select a file : <input type="file" name="file" size="45" accept=".pdf" /></p>
            <input type="submit" value="Upload PDF" />
             
        </form>
     
    </body>
</html>

Now hit the URL : “http://localhost:8080/JerseyDemos/fileUpload.html” and it will display a HTML file control to browse the file. Select any PDF file and click on “Upload PDF” button.

Your file will be uploaded and you will get the message: “Data uploaded successfully !!”

Test file upload using java client

If you are looking for uploading files using java clients then you can modify below working code as per your need.

public static void main(String[] args) throws IOException 
{
    final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
 
    final FileDataBodyPart filePart = new FileDataBodyPart("file", new File("C:/temp/sample.pdf"));
    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
    final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart.field("foo", "bar").bodyPart(filePart);
      
    final WebTarget target = client.target("http://localhost:8080/JerseyDemos/rest/upload/pdf");
    final Response response = target.request().post(Entity.entity(multipart, multipart.getMediaType()));
     
    //Use response object to verify upload success
     
    formDataMultiPart.close();
    multipart.close();
}

 

How to Jersey File Upload Example

In this Jersey tutorial, we will be learning to upload binary files(e.g. PDF files in this example) using Jersey’s multipart form data support. We will learn below required changes to complete the functionality.

Posted on 05-08-2016 

Comment:

To comment you must be logged in members.

Files with category

  • Mini Youtube Using ReactJS

    Mini Youtube Using ReactJS

    View: 156    Download: 3   Comment: 0

    Category: Javascript     Fields: none

    This is one the best starter for ReactJS. MiniYoutube as the name suggests is a youtube like website developed using reactJS and youtube API. This project actually let's you search , play and list youtube videos. Do check it out and start learning...

  • AngularJS and REST API

    AngularJS and REST API

    View: 309    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    This is a tutorial for those interested in a quick introduction to AngularJS and REST API. We will build the familiar Periodic Table of the Elements found in every chemistry textbook, and allow the user to select a Chemical Element by clicking on...

  • Collective Intelligence, Recommending Items Based on Similar Users' Taste

    Collective Intelligence, Recommending Items Based on Similar Users' Taste

    View: 242    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Using Collaborative Filtering to find people who share tastes, and for making automatic recommendations based on things that other people like.

  • Think Like a Bird for Better Parallel Programming

    Think Like a Bird for Better Parallel Programming

    View: 219    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Coding an application to run in parallel is hard, right? I mean, it must be hard or we’d see parallel programs everywhere. All we'd see are slick parallel apps that use every available core effortlessly. Instead multi-threaded apps are the exception...

  • Getting Started with the Bing Search APIs

    Getting Started with the Bing Search APIs

    View: 238    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Bing Search API is a set of REST interfaces that find web pages, news, images, videos, entities, related searches, spelling corrections, and more in response to queries from any programming language that can generate a web request. Applications that...

  • Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    View: 558    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Continuous in-line request/result batching, real-time stream sending/processing, asynchronous data transferring and parallel computation for best performance and scalability

  • Iteration Over Java Collections with High Performance

    Iteration Over Java Collections with High Performance

    View: 210    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Java developers usually deal with Collections such as ArrayList, HashSet, Java 8 come with lambda and streaming API helps us to easily work with Collections. In most cases, we work with few thousands of items and performance isn't a concern. But in...

  • SR2JLIB - A Symbolic Regression Library for Java

    SR2JLIB - A Symbolic Regression Library for Java

    View: 210    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Grammar-Guided Genetic Programming library featuring: multi-threading, just-in-time compilation of individuals, dynamic class loading, and JNI interfacing with C/C++ code

 
File suggestion for you
File suggestion for you
File suggestion for you
File suggestion for you
Loading...
Loading...
Loading...
Loading...
File top downloads
File top downloads
File top downloads
File top downloads
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd