Searching...
Sunday, 7 February 2016

Uploading file using RestEasy

08:54

In this example we will see how to upload a file using RestEasy MultipartFormDataInput and Jetty server.

1. Create a maven web project and add below dependencies

<url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.resteasy>3.0.4.Final</version.resteasy>

    </properties>
    <dependencies>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-client</artifactId>
            <version>${version.resteasy}</version>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>jaxrs-api</artifactId>
            <version>${version.resteasy}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-multipart-provider</artifactId>
            <version>${version.resteasy}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxb-provider</artifactId>
            <version>${version.resteasy}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-spring</artifactId>
            <version>${version.resteasy}</version>
        </dependency>
    </dependencies>

 

2. Update web.xml

This is required to load RestEasy servlets

<context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>
    <listener>
        <listener-class>
            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
        </listener-class>
    </listener>
    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

3. Write a service to upload file

package com.vinod.test;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;

@Path("/fileupload")
public class JaxRSFileUploadController {

    @POST
    @Path("/fileupload")
    @Consumes("multipart/form-data")
    @Produces(MediaType.APPLICATION_JSON)
    public Response fileupload(MultipartFormDataInput input) {
        String fileName = "";
        int status = -1;
        Response resp = null;
        try {
            Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
            List<InputPart> inputParts = uploadForm.get("fileUpload");
            for (InputPart inputPart : inputParts) {
                MultivaluedMap<String, String> header = inputPart.getHeaders();
                fileName = getFileName(header);
                File file = new File(fileName);
                InputStream inputStream = inputPart.getBody(InputStream.class, null);
                byte[] bytes = IOUtils.toByteArray(inputStream);
                FileUtils.writeByteArrayToFile(file, bytes);
            }
            System.out.println("File upload completed");
            resp = Response.ok().build();
        } catch (Exception e) {
            e.printStackTrace();
            status = status <= 0 ? 500 : status;
            resp = Response.status(status).header("Warning", e.getMessage()).build();
        }
        return resp;
    }

    private String getFileName(MultivaluedMap<String, String> multivaluedMap) {
        String[] contentDisposition = multivaluedMap.getFirst("Content-Disposition").split(";");
        for (String filename : contentDisposition) {
            if (filename.trim().startsWith("filename")) {
                String[] name = filename.split("=");
                String exactFileName = name[1].trim().replaceAll("\"", "");
                return exactFileName;
            }
        }
        return "temp";
    }
}
 
 
 
4. Update pom.xml jetty configuration

<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.3.v20140905</version>
                <configuration>
                    <scanIntervalSeconds>10</scanIntervalSeconds>
                    <useTestScope>true</useTestScope>
                    <useProvidedScope>true</useProvidedScope>
                    <httpConnector>
                        <port>8081</port>
                    </httpConnector>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

 
5. Run it
 
Use jetty:run maven command to start jetty server and use the below html file to upload the file
 

<html>
<body>
<form method="post" action="http://localhost:8081/fileupload/fileupload" enctype="multipart/form-data">
    <label>Load your file:</label>
    <input type="file" name="fileUpload" />
    <br />
    <input type="submit" value="Upload file" />
</form>
</body>
</html>
 
 

6. Download example

https://github.com/kkvinodkumaran/webservices/tree/master/vinod-rest-file-test

 


0 comments: