Java File Upload REST service

In this tutorial I will explain how to build Java REST web-service to upload files from any client over HTTP.

Uploading files to web-apps is a common task nowadays. A lot of services support uploading pictures or documents on their sites. With Java web services this is easy accomplished. What we need aside form the java web container (provided by your application server like Tomcat, GlassFish or JBoss) is the jersey framework to make it run. First I will show you how to implement the web-service and than give you two examples of clients to use the service.

Java file upload form

Java file upload form

Building the File Upload REST Service

The file is pushed over HTTP POST with encoding type “multipart/form-data” from the client to our web-service. This way you can add multiple parameters to the POST request in addition to the file. Lets start with the requirements. You will need an web/application server like Tomcat, GlassFish or JBoss to deploy the service. In addition we will use jersey framework to build our service endpoint. Please note, GlassFish 4.x version requires jersey version 2 libraries, so if you are using GlassFish 4 use jersey 2.x dependencies in your POM file instead.

For quick reference you can find the entire project in our GitHub repository under

I will post the entire POM file here, but what you need to take into account are the jersey dependencies

<project xmlns="" xmlns:xsi=""


	<name>File Uploader Rest Service</name>



							<!-- this is relative to the pom.xml directory -->


Having all necessary libraries now, lets go ahead and implement the REST service. There are several places in the code below I want to point your attention to. First note the usage of @Consumes(MediaType.MULTIPART_FORM_DATA) as requested encoding type. Second you may want to add additional parameters to the method if you like. For example you may want to pass some description or another text data with your upload. Finally Java will throw an Exception if you try to upload a file into a directory which not exists.  To avoid this issue I created the method createFolderIfNotExists(String dirName).




import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

 * This example shows how to build Java REST web-service to upload files
 * accepting POST requests with encoding type "multipart/form-data". For more
 * details please read the full tutorial on
 * @author
public class FileUploadService {

	/** The path to the folder where we want to store the uploaded files */
	private static final String UPLOAD_FOLDER = "c:/uploadedFiles/";

	public FileUploadService() {

	private UriInfo context;

	 * Returns text response to caller containing current time-stamp
	 * @return error response in case of missing parameters an internal
	 *         exception or success response if file has been stored
	 *         successfully
	public Response uploadFile(
			@FormDataParam("file") InputStream uploadedInputStream,
			@FormDataParam("file") FormDataContentDisposition fileDetail) {

		// check if all form parameters are provided
		if (uploadedInputStream == null || fileDetail == null)
			return Response.status(400).entity("Invalid form data").build();

		// create our destination folder, if it not exists
		try {
		} catch (SecurityException se) {
			return Response.status(500)
					.entity("Can not create destination folder on server")

		String uploadedFileLocation = UPLOAD_FOLDER + fileDetail.getFileName();
		try {
			saveToFile(uploadedInputStream, uploadedFileLocation);
		} catch (IOException e) {
			return Response.status(500).entity("Can not save file").build();

		return Response.status(200)
				.entity("File saved to " + uploadedFileLocation).build();

	 * Utility method to save InputStream data to target location/file
	 * @param inStream
	 *            - InputStream to be saved
	 * @param target
	 *            - full path to destination file
	private void saveToFile(InputStream inStream, String target)
			throws IOException {
		OutputStream out = null;
		int read = 0;
		byte[] bytes = new byte[1024];

		out = new FileOutputStream(new File(target));
		while ((read = != -1) {
			out.write(bytes, 0, read);

	 * Creates a folder to desired location if it not already exists
	 * @param dirName
	 *            - full path to the folder
	 * @throws SecurityException
	 *             - in case you don't have permission to create the folder
	private void createFolderIfNotExists(String dirName)
			throws SecurityException {
		File theDir = new File(dirName);
		if (!theDir.exists()) {


Finally we need to configure our web.xml to register our class as web-service and make it run on startup.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
	xmlns="" xmlns:web=""
	id="WebApp_ID" version="2.5">
		<servlet-name>Jersey REST Service</servlet-name>
		<servlet-name>Jersey REST Service</servlet-name>

That’s it! Now you can build and deploy the WAR file. If you use the exact same names provided in the code above, your service URL (given you run on localhost) will be: http://localhost:8080/FileUploaderRESTService-1/rest/upload

File Upload HTML Form

You can use a very simple HTML post form as client to send files to the server.

Please note the usage of “multipart/form-data” as encoding type. You also need to add an <input> of type file with the name “file”

Choose file to upload<br>
<form action="http://localhost:8080/FileUploaderRESTService-1/rest/upload" method="post" enctype="multipart/form-data">
	<input name="file" id="filename" type="file" /><br><br>
	<button name="submit" type="submit">Upload</button>

As I already mentioned you can add additional data to your request. In this case just don’t forget to handle it in the web-service 🙂

Java File Upload Client

You can create a file upload client for you Android or stand-alone programs in java. I the example below I will use Apache http libraries, you will need this five:

  • commons-logging
  • httpclient
  • httpclient-cache
  • httpcore
  • httpmime
package net.javatutorial.tutorials.clienst;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.util.EntityUtils;

 * This example shows how to upload files using POST requests 
 * with encoding type "multipart/form-data".
 * For more details please read the full tutorial
 * on
 * @author
public class FileUploaderClient {
	public static void main(String[] args) {
		// the file we want to upload
		File inFile = new File("C:\\Users\\admin\\Desktop\\Yana-make-up.jpg");
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(inFile);
			DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
			// server back-end URL
			HttpPost httppost = new HttpPost("http://localhost:8080/FileUploaderRESTService-1/rest/upload");
			MultipartEntity entity = new MultipartEntity();

			// set the file input stream and file name as arguments
			entity.addPart("file", new InputStreamBody(fis, inFile.getName()));

			// execute the request
			HttpResponse response = httpclient.execute(httppost);
			int statusCode = response.getStatusLine().getStatusCode();
			HttpEntity responseEntity = response.getEntity();
			String responseString = EntityUtils.toString(responseEntity, "UTF-8");
			System.out.println("[" + statusCode + "] " + responseString);
		} catch (ClientProtocolException e) {
			System.err.println("Unable to make connection");
		} catch (IOException e) {
			System.err.println("Unable to read file");
		} finally {
			try {
				if (fis != null) fis.close();
			} catch (IOException e) {}

You will find the project files in our GitHub repository

Thanks for reading. As always comments are welcome 🙂

Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+Digg thisPin on PinterestShare on RedditShare on StumbleUponPrint this pageEmail this to someone

2 thoughts on “Java File Upload REST service

  1. Two things:

    First, if I use I the URL
    that is in the form and the text of the example I get a 404 error. That was from the github version of this.

    If I take out the “-1” at the end of the service name and use
    then I got an upload. Is the “-1” just a typo or was it supposed to mean something?

    Secondly, I started looking at this tutorial because of the use of multipart, as I want to add parameters as part of the upload. Is there somewhere I could find an example of that usage?


    1. Thank you for your comment Sandstones! Good remark with the -1 in the service URL.

      How your service URL will look like depends on the way you build and deploy the WAR file:
      1) If you use the approach right click on Project name -> Run As -> Run on Server , the correct URL of the service will be “http://localhost:8080/FileUploaderRESTService/rest/upload”
      2) however if you use maven to build and deploy manually with “mvn clean package” the resulting WAR file will be “FileUploaderRESTService-1.war” . -1 in this case comes from the tag 1 in your POM file and is automatically appended to the filename. Finally when you deploy this WAR to your server (Tomcat, or Glassfish) the URL will be : “http://localhost:8080/FileUploaderRESTService-1/rest/upload”

      To answer your second question: yes you can add additional parameters to the upload request. Lets say for example you want to add the name of the file uploader along with the same request. In your HTML form just add an additional <input> like this:
      <input type="text" name="uploader" value="John" />

      … or if you use the Java client (found here add this line:
      entity.addPart("uploader", new StringBody("John));

      finally you need to update your web-service method to accept this new parameter by adding a new @FormDataParam in the uploadFile method like this:

      public Response uploadFile(
      @FormDataParam("file") InputStream uploadedInputStream,
      @FormDataParam("file") FormDataContentDisposition fileDetail,
      @FormDataParam("uploader") String uploaderName) {

      Hope this helps!

Leave a Reply