Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Upload Multiple Files Jersey REST API

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 5.63k
    Comment on it

    Jersey Rest API also know as JAX-RS "Java API for RESTful Web Services" is a an open source web service framework which is used to develop Java RESTful WEB Services.
    In this tutorial we will learn to upload multiple file using Jersey REST API.
    To know how to do that, see below steps

     

    Step 1: Define Jersey dependencies in your pom

    <dependency>
    	<groupId>com.sun.jersey</groupId>
    	<artifactId>jersey-server</artifactId>
    	<version>1.8</version>
    </dependency>
    	
    <dependency>
    	<groupId>com.sun.jersey.contribs</groupId>
    	<artifactId>jersey-multipart</artifactId>
    	<version>1.8</version>
    </dependency>
    	
    <!-- Apache Commons Upload -->
    <dependency>
    	<groupId>commons-fileupload</groupId>
    	<artifactId>commons-fileupload</artifactId>
    	<version>1.2.2</version>
    </dependency>
    
    <!-- Apache Commons Upload -->
    <dependency>
    	<groupId>commons-io</groupId>
    	<artifactId>commons-io</artifactId>
    	<version>1.3.2</version>
    </dependency>

     

    Step 2: Configure Jersey Servlet Container in your web.xml.

    <servlet>
    	<servlet-name>Rest Service</servlet-name>
    	<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    	<init-param>
    		<param-name>com.sun.jersey.config.property.packages</param-name>
    		<param-value>com.evontech.blog</param-value>
    	</init-param>
    	<init-param>
    		<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    		<param-value>true</param-value>
    	</init-param>
    	<load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    	<servlet-name>Rest Service</servlet-name>
    	<url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

     

    Step 3: Define your upload controller.

    package com.evontech.blog;
    
    import java.io.File;
    import java.util.Iterator;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    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.Context;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    
    @Path("/upload")
    public class UploadController {
    
    	private static final String FILE_UPLOAD_PATH = "D:\\Upload";
    
    	@POST
    	@Consumes(MediaType.MULTIPART_FORM_DATA)
    	@Produces("text/plain")
    	@Path("/multipleFiles")
    	public Response uploadFile(@Context HttpServletRequest request) {
    
    		String name = null;
    		int code = 200;
    		String msg = "Files uploaded successfully";
    		if (ServletFileUpload.isMultipartContent(request)) {
    			FileItemFactory factory = new DiskFileItemFactory();
    			ServletFileUpload fileUpload = new ServletFileUpload(factory);
    			try {
    
    				List<FileItem> items = fileUpload.parseRequest(request);
    
    				if (items != null) {
    					Iterator<FileItem> iter = items.iterator();
    					/*
    					 * Return true if the instance represents a simple form
    					 * field. Return false if it represents an uploaded file.
    					 */
    					while (iter.hasNext()) {
    						final FileItem item = iter.next();
    						final String itemName = item.getName();
    						final String fieldName = item.getFieldName();
    						final String fieldValue = item.getString();
    
    						if (item.isFormField()) {
    							name = fieldValue;
    							System.out.println("Field Name: " + fieldName + ", Field Value: " + fieldValue);
    							System.out.println("Candidate Name: " + name);
    						} else {
    							final File file = new File(FILE_UPLOAD_PATH	+ File.separator + itemName);
    							File dir = file.getParentFile();
    							if(!dir.exists()) {
    								dir.mkdir();
    							}
    							
    							if(!file.exists()) {
    								file.createNewFile();
    							}
    							System.out.println("Saving the file: " + file.getName());
    							item.write(file);
    						}
    
    					}
    				}
    			} catch (FileUploadException e) {
    				code = 404;
    				msg = e.getMessage();
    				e.printStackTrace();
    			} catch (Exception e) {
    				e.printStackTrace();
    				code = 404;
    				msg = e.getMessage();
    			}
    		}
    
    		return Response.status(code).entity(msg).build();
    	}
    }
    

     

    Step 4: Let's create a JSP to test the functionality.

    <html>
    <head>
    <title>Multiple File Upload Example</title>
    </head>
    <body>
    	<form action="rest/upload/multipleFiles" method="POST" enctype="multipart/form-data">
    		<div id="fileSection">
    			<h1>Multiple File Upload Application</h1>
    			<table>
    				<tr>
    					<td>Name:</td>
    					<td><input type="text" name="candidateName" size="45" /></td>
    				</tr>
    				<tr>
    					<td>Resume</td>
    					<td><input type="file" name="infoFile" size="45" /></td>
    				</tr>
    				<tr>
    					<td>Photo</td>
    					<td><input type="file" name="imgFile" size="45" /></td>
    				</tr>
    			</table>
    		</div>
    		<p />
    		<input type="submit" value="Upload" />
    	</form>
    </body>
    </html>
    

    Done.

    Thanks. Happy Coding.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: