25

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

yurib
  • 8,043
  • 3
  • 30
  • 55
Michael Neale
  • 19,248
  • 19
  • 77
  • 109
  • Checkout my answer [here](https://stackoverflow.com/a/73128383/1547266) that is vendor agnostic. – Arthur Jul 30 '22 at 10:30

1 Answers1

30

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
}
ra9r
  • 4,528
  • 4
  • 42
  • 52
  • 1
    raiglstorfer, how would you setup the request to test this service? – c12 Apr 20 '11 at 23:31
  • 1
    @c12 I use cURL to test my RESTeasy methods. Something like this should work: `curl -F filedata=@yourfile.png http://localhost:8080/Project/rest-servlet/upload`, more info here: [link](http://curl.haxx.se/) – François Cassin Jun 23 '11 at 10:14
  • What about Resteasy reactive support? https://quarkus.io/guides/resteasy-reactive#multipart – user1653042 Apr 30 '23 at 04:10