Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a multipart/form file upload with jax-rs?

(specifically RESTeasy)

It would be nice (for a single file) to have a method signature like:

public void upload(@FormParam("name") ..., @FormParam("file") file: InputStream) ...  

doable? or am I dreaming? doesn't seem to be that simple.

like image 662
Michael Neale Avatar asked Apr 14 '10 11:04

Michael Neale


People also ask

How do I upload a multipart form data?

Follow this rules when creating a multipart form: Specify enctype="multipart/form-data" attribute on a form tag. Add a name attribute to a single input type="file" tag. DO NOT add a name attribute to any other input, select or textarea tags.

How does multipart file upload work?

Multipart upload allows you to upload a single object as a set of parts. Each part is a contiguous portion of the object's data. You can upload these object parts independently and in any order. If transmission of any part fails, you can retransmit that part without affecting other parts.

How do you send a multipart file in RestTemplate?

Set the content-type header value to MediaType. MULTIPART_FORM_DATA. When this header is set, RestTemplate automatically marshals the file data along with some metadata. Metadata includes file name, file size, and file content type (for example text/plain):


1 Answers

The key is to leverage the @MultipartForm annotations that comes with RESTEasy. This enables you to define a POJO that contains all the parts of the form and bind it easily.

Take for example the following POJO:

public class FileUploadForm {     private byte[] filedata;      public FileUploadForm() {}      public byte[] getFileData() {         return filedata;     }      @FormParam("filedata")     @PartType("application/octet-stream")     public void setFileData(final byte[] filedata) {         this.filedata = filedata;     } } 

Now all you need to do is use this POJO in the entity which would look something like this:

@POST @Path("/upload") @Consumes("multipart/form-data") public Response create(@MultipartForm FileUploadForm form)  {     // Do something with your filedata here } 
like image 157
ra9r Avatar answered Sep 20 '22 11:09

ra9r