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
URL : http://localhost:8080/RESTfulExample/rest/file/upload
Download Source Code
Download it – JAX-RS-FileUpload-Jersey-Example.zip (6 KB)
How can I call this via a CURL request in php ?
should uploadedInputStream be closed?
For me bad request
It Is Showing Unsupported Media Type Please help.
you simply need to add mimepull.jar to your lib
Me too have same problem..
[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?
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 .
I’ve test this and everything seem to be find but when I try to open file that I uploaded the file is corrupted.
This code will not work for large size files.
Hi mkyong,
Hello just a quick question how do you run this locally? mvn spring-boot:run is not working on me kindly help me please
What is FormDataContentDisposition? Why is it used?
hello i am using this code for file upload but not getting enough speed while using tomcat as server can you please help
how to do multiple file uploads
// delete the following line, you already opened the output stream right after the
try
.out = new FileOutputStream(new File(uploadedFileLocation));
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?
How to send the fire from Android to this web service?
How to use jersey-multipart in Glassfish 4.1.1?
How to use jersey-multipart in Glassfish server?
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
Hi Sir,
How to send json data and uploading file to Rest full web service in a single request?
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
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]
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.
hi i’m new to jquery and webservices… is it possible to upload file using jquery ajax and rest web service.
yes no probelem with processing the uploading file but limit size of kb only
how to write the test to this.
it’s difficult to realize.
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???
Hi,
It is not working for simultaneous uploading files.
org.glassfish.jersey.servlet.ServletContainer i have this problem
How to apply this example without Maven.. I am using Eclipse + Tomcat 7 + Jersey (no Maven)
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…
mkyong the best the java progaraming to the application devaloperment
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?