How can I upload image and data in the same request with angular and resteasy?
Technically, you can just get both pieces of data from the MultipartFormDataInput
. For example
<form action="api/upload" method="post" enctype="multipart/form-data"> Choose a file : <input type="file" name="file" /> First name: <input type="text" name="firstname" /> List name: <input type="text" name="lastname" /> <input type="submit" value="Upload" /></form>@Consumes(MediaType.MULTIPART_FORM_DATA)public Response upload(MultipartFormDataInput multipart) throws IOException { try (InputStream in = multipart.getFormDataPart("file", InputStream.class, null); FileOutputStream fos = new FileOutputStream("file.png")) { byte[] buff = new byte[1024]; int count; while ((count = in.read(buff)) != -1) { fos.write(buff, 0, count); } } String firstname = multipart.getFormDataPart("firstname", String.class, null); String lastname = multipart.getFormDataPart("lastname", String.class, null); return Response.ok(firstname + ":" + lastname).build();}
If you want to put everything into a POJO, you can do something like this
public class MyEntity { @FormParam("firstname") private String firstname; @FormParam("lastname") private String lastname; @FormParam("file") private byte[] file; // Getter and Setters}
Then in your resource method
@Consumes(MediaType.MULTIPART_FORM_DATA)public Response upload(@MultipartForm MyEntity entity) throws IOException { try (FileOutputStream fos = new FileOutputStream("file.png")) { byte[] filebytes = entity.getFile(); fos.write(filebytes); } String firstname = entity.getFirstname(); String lastname = entity.getLastname(); return Response.ok(firstname + ":" + lastname).build();}
See more: