Main Tutorials

File upload example in Jersey

In this tutorial, we show you how do to file upload with Jersey, JAX-RS implementation.

1. Jersey Multipart Dependency

To support multipart (file upload) in Jersey, you just need to include “jersey-multipart.jar” in Maven pom.xml file.


<project ...>

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

	<dependencies>

		<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>

	</dependencies>

</project>

2. File Upload HTML Form

Simple HTML form to select and upload a file.


<html>
<body>
	<h1>File Upload with Jersey</h1>
 
	<form action="rest/file/upload" method="post" enctype="multipart/form-data">
 
	   <p>
		Select a file : <input type="file" name="file" size="45" />
	   </p>
 
	   <input type="submit" value="Upload It" />
	</form>
 
</body>
</html>

3. Upload Service with Jersey

In Jersey, use @FormDataParam to receive the uploaded file. To get the uploaded file name or header detail, match it to “FormDataContentDisposition“.


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("/file")
public class UploadFileService {

	@POST
	@Path("/upload")
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	public Response uploadFile(
		@FormDataParam("file") InputStream uploadedInputStream,
		@FormDataParam("file") FormDataContentDisposition fileDetail) {

		String uploadedFileLocation = "d://uploaded/" + fileDetail.getFileName();

		// save it
		writeToFile(uploadedInputStream, uploadedFileLocation);

		String output = "File uploaded to : " + uploadedFileLocation;

		return Response.status(200).entity(output).build();

	}

	// save uploaded file to new location
	private void writeToFile(InputStream uploadedInputStream,
		String uploadedFileLocation) {

		try {
			OutputStream out = new FileOutputStream(new File(
					uploadedFileLocation));
			int read = 0;
			byte[] bytes = new byte[1024];

			out = new FileOutputStream(new File(uploadedFileLocation));
			while ((read = uploadedInputStream.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			out.flush();
			out.close();
		} catch (IOException e) {

			e.printStackTrace();
		}

	}

}

4. Demo

Select a file and click on the upload button, the selected file is uploaded to a pre-defined location.

URL : http://localhost:8080/RESTfulExample/FileUpload.html

file upload demo 1

URL : http://localhost:8080/RESTfulExample/rest/file/upload

file upload in demo 2

Download Source Code

Download it – JAX-RS-FileUpload-Jersey-Example.zip (6 KB)

References

  1. Jersey Official Website
  2. File Upload example in RESTEasy

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
124 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Prashant Sharma
6 years ago

How can I call this via a CURL request in php ?

Kent Chen
8 years ago

should uploadedInputStream be closed?

Alex
6 years ago

For me bad request

Aman
6 years ago

It Is Showing Unsupported Media Type Please help.

Guest
6 years ago
Reply to  Aman

you simply need to add mimepull.jar to your lib

Bhuvanesh
6 years ago
Reply to  Aman

Me too have same problem..

Cristo J. Reyes Rodríguez
8 years ago

[FATAL] No injection source found for a parameter of type public javax.ws.rs.core.Response

With jersey 2.16

any solution? maybe adding parameters to web.xml?

Swapnil Kurhekar
9 years ago

Hi mkyong ,
Great example . it works for me and got file uploaded to server location but my problem is after file upload any other POST request gives me “415 Unsupported media type” error. i am using jersey multipart 1.8 , mimepull 1.9.4 and all jersey jar with 1.8 versions . i am testing my rest service over advance rest client chrome extension. please help me …..got stuck to it from many days .

test
9 years ago

I’ve test this and everything seem to be find but when I try to open file that I uploaded the file is corrupted.

AmitD
1 year ago

This code will not work for large size files.

brayan
3 years ago

Hi mkyong,

now if the case of zip file instead of png (aqw.zip), it is the same code at jesery level ?
thank you in advance
Dominic Hong
3 years ago

Hello just a quick question how do you run this locally? mvn spring-boot:run is not working on me kindly help me please

hitesh
4 years ago

What is FormDataContentDisposition? Why is it used?

darshit parekh
5 years ago

hello i am using this code for file upload but not getting enough speed while using tomcat as server can you please help

Vss
5 years ago

how to do multiple file uploads

Adelaide
6 years ago

// delete the following line, you already opened the output stream right after the try.
out = new FileOutputStream(new File(uploadedFileLocation));

AY.B
6 years ago

hello evreybody
when i want upload file i have this message
Etat HTTP 404 – Servlet jersey-serlvet n’est pas disponible.

type Rapport dӎtat

message Servlet jersey-serlvet n’est pas disponible.

description La ressource demandée (Servlet jersey-serlvet n’est pas disponible.) n’est pas disponible.

….
to resume jersey-serlvet not found
can you hlep me?

Sarith Nob
6 years ago

How to send the fire from Android to this web service?

Sarith Nob
6 years ago

How to use jersey-multipart in Glassfish 4.1.1?

Sarith Nob
6 years ago

How to use jersey-multipart in Glassfish server?

Tarmizi Hamid
6 years ago

I don’t understand how the html file was related to java class, I have tried this example but I don’t use maven anymore, only Java Web Dinamic Project. It does not work, the html file didn’t call the java class anymore

Bhimaraya
7 years ago

Hi Sir,
How to send json data and uploading file to Rest full web service in a single request?

lakshminarayana
6 years ago
Reply to  Bhimaraya

just now create the file input src foledder kabf rb the frist if we wanto create the the input steream in file uploading in conversion team in that if u want to create the files of application the servce the implementation appalivcation try to understand teach the fil;e the job a

Pun Lok
7 years ago

Hi ,
How can we upload .txt file from java application (software) to webservice? I can pass string parameter but can’t do with file or some object. Actually I will have some sql query inside .txt file and want to upload it to server then execute all query inside server. How is it possible?

If anybody know please help me : or email me : [email protected]

NIL
7 years ago

For this function my application works perfect public Response uploadFile(@FormDataParam(“file”) InputStream uploadedStream) {

But
When i am writing method like public Response uploadFile(@FormDataParam(“file”) InputStream uploadedStream, @FormDataParam(“ddd”) String ddd, @FormDataParam(“id”) Long id) {

my application stop working any suggestion.

Sanjeeve
7 years ago

hi i’m new to jquery and webservices… is it possible to upload file using jquery ajax and rest web service.

lakshminarayana
6 years ago
Reply to  Sanjeeve

yes no probelem with processing the uploading file but limit size of kb only

brucelv
8 years ago

how to write the test to this.

Cheng
8 years ago
Reply to  brucelv

it’s difficult to realize.

ScienceDiscovery
8 years ago

Hi JerseyMan, I got right now the same problem with the 10kb limit which seems to be appeared from nowhere. Did you found a solution???

munisekhar rangineni
9 years ago

Hi,

It is not working for simultaneous uploading files.

mahesh
9 years ago

org.glassfish.jersey.servlet.ServletContainer i have this problem

Techna
9 years ago

How to apply this example without Maven.. I am using Eclipse + Tomcat 7 + Jersey (no Maven)

Jalex
9 years ago

I am pretty irritated that someone posted a link to mkyong.com from stackoverflow and didn’t get voted down. This site has always been a misleading place, with bits of valuable information diluted with broken code, examples and lack of real knowledge about any of the subjects covered. Not surprised at all that people had trouble running the code. Please don’t send people to this site…

lakshminarayana
6 years ago
Reply to  Jalex

mkyong the best the java progaraming to the application devaloperment

aarthi
9 years ago

Hello, I am not able to get this to work: Caused By: java.lang.IllegalArgumentException: The MultiPartConfig instance we expected is not present. Have you registered the MultiPartConfigProvider class?

How do I fix this?