Anil Verma
Anil Verma

Reputation: 51

How to upload csv files through Rest APIs using Jersey (Java)?

I have a requirement to upload csv file through upload API but having difficulty to add thta support in framework. I am using jersey as tool and using below maven dependency for multipart support.

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

Please help with some sample code to help me implement file upload (csv, xlsx etc.) via Rest API.

Upvotes: 1

Views: 8792

Answers (1)

cassiomolin
cassiomolin

Reputation: 131037

To upload a file to the server, you can send the file content in the request payload using, for example, POST. The Content-Type of the request should be multipart/form-data and your resource method must be annotated with @Consumes(MediaType.MULTIPART_FORM_DATA).

In Jersey you could use the @FormDataParam annotation to bind the named body part(s) of a multipart/form-data request entity body to a resource method parameter, as following:

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(@FormDataParam("file") InputStream inputStream,
                       @FormDataParam("file") FormDataContentDisposition fileMetaData) {
    ...
}

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

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

If you're not using Maven make sure to have all needed dependencies (see jersey-media-multipart) on the classpath.

You also need to register the MultiPartFeature in your Application / ResourceConfig sub-class:

@ApplicationPath("/api")
public class MyApplication extends Application {
   
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(MultiPartFeature.class);
        return classes;
    }
}
@ApplicationPath("/api")
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        register(MultiPartFeature.class);
    }
}

For more details, check the Jersey documentation about multipart requests.

If you need to manipulate XLS/XLSX files, you can consider the Apache POI project.

Upvotes: 3

Related Questions