1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.