Home > General > File upload and download with Jersy and Maven

File upload and download with Jersy and Maven

September 2, 2011

pom.xml file

<xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
 <groupId>com.test</groupId>
 <artifactId>filedownload</artifactId>
 <version>0.0.1</version>
 <packaging>war</packaging>
 <properties>
 <apacheds.version>1.5.5</apacheds.version>
 <client.shared.version>1.0</client.shared.version>
 <password.vault.pojo.version>1.0</password.vault.pojo.version>
 <cxf.version>2.3.1</cxf.version>
 </properties>
 <dependencies>
 <dependency>
 <groupId>log4j</groupId>
 <artifactId>log4j</artifactId>
 <version>1.2.14</version>
 </dependency>
 <dependency>
 <groupId>org.slf4j</groupId>
 <artifactId>slf4j-log4j12</artifactId>
 <version>1.5.2</version>
 </dependency>

<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.2.1</version>
 </dependency>
 <dependency>
 <groupId>com.sun.jersey</groupId>
 <artifactId>jersey-server</artifactId>
 <version>1.1.0-ea</version>
 </dependency>
 <!-- depend on JAXB to enable WADL support -->
 <dependency>
 com.sun.xml.bind
 <artifactId>jaxb-impl</artifactId>
 <version>2.1.10</version>
 </dependency>
 <dependency>
 <groupId>org.mortbay.jetty</groupId>
 <artifactId>servlet-api-2.5</artifactId>
 <version>6.1.14</version>
 <scope>provided</scope>
 </dependency>
 <dependency>
 <groupId>bouncycastle</groupId>
 <artifactId>bcprov-jdk15</artifactId>
 <version>140</version>
 </dependency>
 <dependency>
 <groupId>commons-io</groupId>
 <artifactId>commons-io</artifactId>
 <version>2.0.1</version>
 <type>jar</type>
 <scope>compile</scope>
 </dependency>
 </dependencies>

<repositories>
 <repository>
 <id>maven2-repository.dev.java.net</id>
 <name>Java.net Repository for Maven</name>
 <url>http://download.java.net/maven/2/</url>
 <layout>default</layout>
 </repository>
 </repositories>

<build>
 <plugins>
 <plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-compiler-plugin</artifactId>
 <version>2.0.2</version>
 <configuration>
 <source>1.6</source>
 <target>1.6</target>
 <optimize>true</optimize>
 <showDeprecations>true</showDeprecations>
 <encoding>ISO-8859-1</encoding>
 </configuration>
 </plugin>
 <plugin>
 <groupId>org.mortbay.jetty</groupId>
 <artifactId>maven-jetty-plugin</artifactId>
 <version>6.1.16</version>
 <configuration>
 <scanIntervalSeconds>60</scanIntervalSeconds>
 <contextPath>/${project.artifactId}</contextPath>
 <systemProperties>
 <systemProperty>
 <key>jetty.port</key>
 <value>7009</value>
 </systemProperty>
 </systemProperties>
 </configuration>
 </plugin>
 </plugins>
 </build>
 </project>

Java Source code.

package com.test;
import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.List;

import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.GET;
 import javax.ws.rs.POST;
 import javax.ws.rs.Path;
 import javax.ws.rs.Produces;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.Response.ResponseBuilder;
 import javax.ws.rs.core.Response.Status;

import org.apache.commons.fileupload.FileItem;
 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
 import org.apache.commons.fileupload.servlet.ServletFileUpload;

@Path("/config")
 public class FileDownloadUpLoadTest
 {
 private static final int MAX_FILE_SIZE = 2 * 1024 * 1024;

@GET
 @Path("downloadFile")
 @Produces("application/octet-stream")
 public Response downloadKeyStore()
 {
 ResponseBuilder builder = Response.status( Status.OK );
 try
 {
 File file = new File("/home/mindtree/Desktop/jxbrowser-2.9.jar");
 FileInputStream fis = new FileInputStream(file);
 ByteArrayOutputStream bos = new ByteArrayOutputStream();
 byte[] buf = new byte[1024];
 for (int readNum; (readNum = fis.read(buf)) != -1;)
 {
 bos.write(buf, 0, readNum);
 }
 builder.entity(bos.toByteArray());

} catch (IOException ex)
 {
 ex.printStackTrace();
 }

return builder.build();
 }

@POST
 @Path("uploadFile")
 @Consumes("multipart/form-data")
 @Produces("text/html")
 public String uploadKeystore( @Context HttpServletRequest request )
 {
 byte[] data = null;
 String fileName = null;
 try
 {
 DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
 fileItemFactory.setRepository(new File("/tmp"));

ServletFileUpload fileUpload = new ServletFileUpload( fileItemFactory );
 fileUpload.setSizeMax( 2 * MAX_FILE_SIZE ); // set the request max size to twice the max file size

List fileItems = fileUpload.parseRequest( request );

for ( FileItem fi : fileItems )
 {
 if ( fi.isFormField() )
 {
 System.out.println( "form field "+ fi );
 }
 else
 {
 String fieldName = fi.getFieldName();
 System.out.println("fieldName"+fieldName);

fileName = fi.getName();
 System.out.println("fileName"+fileName);

String contentType = fi.getContentType();
 System.out.println("contentType"+contentType);

boolean isInMemory = fi.isInMemory();
 System.out.println("isInMemory"+isInMemory);

long sizeInBytes = fi.getSize();
 System.out.println("sizeInBytes"+sizeInBytes);

data = fi.get();
 }
 }

//below is the different part
 File someFile = new File(fileName);
 FileOutputStream fos = new FileOutputStream(someFile);
 fos.write(data);
 fos.flush();
 fos.close();

System.out.println("uploaded successfully");
 }
 catch ( Exception e )
 {
 e.printStackTrace();
 }

return "uploaded successfully";
 }
 }

web.xml file

<?xml version="1.0" encoding="UTF-8"?>

<!--DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
 <web-app>

<listener>
 <listener-class>
 org.apache.commons.fileupload.servlet.FileCleanerCleanup
 </listener-class>
 </listener>

<servlet>
 <servlet-name>Jersey-REST-servlet</servlet-name>
 <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
 <init-param>
 com.sun.jersey.config.property.packages
 <param-value>com.test</param-value>
 </init-param>
 </servlet>

<servlet-mapping>
 <servlet-name>Jersey-REST-servlet</servlet-name>
 /pv/*
 </servlet-mapping>

<welcome-file-list>
 config.html
 </welcome-file-list>
 </web-app>

HTML File.
This includes Jquery files.Download jquery and add to the project path.

<!--DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <title>File download and upload sample</title>
 css" href="css/jquery-ui-1.7.2.custom.css"
 rel="stylesheet" />
 <script type="text/// <![CDATA[
 javascript" src="js/jquery-1.3.2.min.js">
 // ]]>
 <script type="text/// <![CDATA[
 javascript" src="js/jquery-ui-1.7.2.custom.min.js">
 // ]]>
 <script type="text/javascript">
 $(function()
 {
 $("#tabs").tabs();
 });

$(document).ready(function()
 {
 $("#submitFrame").load(function(){
 var jsonResult = jQuery(submitFrame.document.body).html();
 showDialog( jsonResult );
 } );
 });
 function showDialog( text )
 {
 $("#dialog").attr({ innerHTML: text });
 $("#dialog").dialog(
 {
 bgiframe: true,
 modal: false,

});
 $("#dialog").dialog( 'open' );
 }
 </script>
 </head>
 <body>
 <div>
<div>20px; padding: 0 .7em;"></div>
<p align="center">File Download and Upload Sample</p>
 </div>
 </div>
 <br />
 <div id="tabs">
 <ul>
 <li><a href="#tabs-1">Download File</a></li>
 <li><a href="#tabs-2">Upload File</a></li>
 </ul>
<div id="tabs-1">1px solid black; text-align: left;"></div>
<a href="pv/config/downloadFile"> Click here to download the file</a>
 </div>
<div id="tabs-2">1px solid black; text-align: left;"></div>
<form id="uploadKeyForm" method="post" enctype="multipart/form-data" action="pv/config/uploadFile" target="submitFrame">
 <table width="100%">
 <tr>
 <td>
 <table>
 <tr>
 <td>File:</td>
 <td><input id="ks" name="ks" type="file"></td>
 </tr>
 <tr>
 <td><input type="submit" id="uploadKey" value="Upload Keys"></td>
 </tr>
 </table>
 </td>
 </tr>
 </table>
 </form>
 <iframe id="submitFrame" name="submitFrame"
 style="display: none; visibility: hidden"> </iframe></div>
 </div>
 </div>
 <!-- end of tabs div -->
 <div id="dialog" title="Vault Configurator"></div>
 </body>
 </html>
Advertisements
Categories: General
%d bloggers like this: