Loading...

How to Jersey File Upload Example

View: 533    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: 98    Download: 2   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...

  • Angular 6 Starter with Laravel 5.6 API Service

    Angular 6 Starter with Laravel 5.6 API Service

    View: 136    Download: 1   Comment: 0

    Category: Javascript     Fields: none

    Angular 6 and Laravel 5.6 This project is a starter for creating interface with Angular using bootstrap && css && sass and using Laravel 5.6 for api requests. Demo Installation This project is divided in two parts (projects) and before use them you...

  • Simple Richtext Editor Based on pellJS

    Simple Richtext Editor Based on pellJS

    View: 65    Download: 0   Comment: 0

    Category: Javascript     Fields: none

    A simple visual editor for websites using the pell javascipt. It also has the option to switch between visual editor mode and source code mode. I will upload an update for new functionality soon. Source Code Editor Visual Editor

  • Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    View: 91    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    With the Active Reports Server, you can have a multi-tenant environment where users from various departments, companies, or other specifications can log in, view their reports (and only their reports), export the data, or set up a distribution...

  • AngularJS and REST API

    AngularJS and REST API

    View: 274    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: 220    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: 199    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: 217    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...

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