(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.
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.
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.
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):
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With