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

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

Comments

avatar
87 Comment threads
36 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
100 Comment authors
hiteshdarshit parekhVssAdelaideAlex Recent comment authors
newest oldest most voted
Swapnil Kurhekar
Guest
Swapnil Kurhekar

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 .

Aman
Guest
Aman

It Is Showing Unsupported Media Type Please help.

Bhuvanesh
Guest
Bhuvanesh

Me too have same problem..

Guest
Guest
Guest

you simply need to add mimepull.jar to your lib

Kent Chen
Guest
Kent Chen

should uploadedInputStream be closed?

Prashant Sharma
Guest
Prashant Sharma

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

Alex
Guest
Alex

For me bad request

Jalex
Guest
Jalex

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

mkyong the best the java progaraming to the application devaloperment

Adelaide
Guest
Adelaide

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

AY.B
Guest
AY.B

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
Guest
Sarith Nob

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

Sarith Nob
Guest
Sarith Nob

How to use jersey-multipart in Glassfish 4.1.1?

Sarith Nob
Guest
Sarith Nob

How to use jersey-multipart in Glassfish server?

Tarmizi Hamid
Guest
Tarmizi Hamid

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

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

lakshminarayana
Guest
lakshminarayana

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
Guest
Pun Lok

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 : java.lok2011@gmail.com

NIL
Guest
NIL

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

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

lakshminarayana
Guest
lakshminarayana

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

brucelv
Guest
brucelv

how to write the test to this.

Cheng
Guest
Cheng

it’s difficult to realize.

ScienceDiscovery
Guest
ScienceDiscovery

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

Cristo J. Reyes Rodríguez
Guest
Cristo J. Reyes Rodríguez

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

munisekhar rangineni
Guest
munisekhar rangineni

Hi,

It is not working for simultaneous uploading files.

mahesh
Guest
mahesh

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

Techna
Guest
Techna

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

test
Guest
test

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

aarthi
Guest
aarthi

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?

Rodrigo Silveira
Guest
Rodrigo Silveira

A simple, and perhaps embarrassing to me, question: The example does not include other form attributes and I’m struggling with finding the best way to collect additional attributes, as for instance a text field including comments about the uploaded file. Any suggestions would be very welcome.

Simon Lieschke
Guest
Simon Lieschke

It’s not a good idea to use untrusted information from the client to work out the path to save the file on the file system. This could easily be exploited to attack the system. See https://www.owasp.org/index.php/Unrestricted_File_Upload for more details about why this is extremely bad practise.

It would be great if you could update your example as many people won’t read down to the comments.

Koiky
Guest
Koiky

Hi !

I had an error 405 : Method not allowed with this tuto and I found a solution, I think… But I don’t know if a good answer.

So, to explain I had an error when I use @PathParam in a other tuto in this website and I read that it was necessary to use @Produces() so I tried to do the same here by putting @Produces(MediaType.TEXT_PLAIN) and it works !

But I wonder if it’s a good way… ?

Thank

Camilo Lopes
Guest
Camilo Lopes

It did not work for me.
HTTP Status 415 – Unsupported Media Type

tehCivilian
Guest
tehCivilian

Include the mimepull-X.X.jar to solve the problem with the HTTP Status 415 in your devolpment environment.

Link: http://download.java.net/maven/2/org/jvnet/mimepull/

Iury Lira
Guest
Iury Lira

Hi Mkyong,

I need to make a java rest service to upload, process and download the processed image to user. Do you suggest a synchronous or asynchronous service?

Regards,

Iury

Diego
Guest
Diego

hello,

I have a problem with my service and I could not find a solution.

this is the console message.

Grave: A message body reader for Java class com.sun.jersey.multipart.FormDataMultiPart, and Java type class com.sun.jersey.multipart.FormDataMultiPart, and MIME media type application/octet-stream was not found.

if anyone knows how to solve it would greatly appreciate your support

Rajesh Yadav
Guest
Rajesh Yadav

Just put mimepull-1.9.4.jar into WEB-INF/lib directory to solve this issue.