1

I was wondering how to make an http post request to Jersey with a JSON object containing the following:

export interface JobData {
    providerId: number,
    jobProvided: string,
    jobCategory: string,
    price: number,
    description: string,
    images: File[],
    paused?: boolean
}

In the backend:

    @POST
    @Path("/new")
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    public Response newJobPost(@Valid final JobDto jobDto) throws IOException {

        LOGGER.info("Accessed /jobs/new POST controller");

        final User user = userService.getUserByEmail(jobDto.getProviderId()+"").orElseThrow(UserNotFoundException::new);

        Map<String, List<FormDataBodyPart>> map = jobDto.getImages().getFields();
        List<NewImageDto> imagesDto = new LinkedList<>();

        for (Map.Entry<String, List<FormDataBodyPart>> entry : map.entrySet()) {

            for (FormDataBodyPart part : entry.getValue()) {
                InputStream in = part.getEntityAs(InputStream.class);
                imagesDto.add(new NewImageDto(IOUtils.toByteArray(in), part.getMediaType().toString()));
            }
        }

        final Job job = jobService.createJob(jobDto.getJobProvided(), jobDto.getCategory(), jobDto.getDescription(), jobDto.getPrice(), false, imagesDto, user);
        return Response.ok().build();
    }

Inside JobDto there is a variable of type FormDataMultiPart called images. The problem i'm having is that when i make the post request, i get an error: 415 Unsupported Media Type. To make the request i'm using angular:

createJob(jobData: JobData) {
    return this.http.post<JobData>(environment.apiBaseUrl + '/jobs/new', jobData);
  }
  • 1
    You need to use js FormData to send multipart. Your parameter in Jersey will have to be of type FormDataMultiPart (you can't use a POJO) and you will need to manually extract your parts. Search for how to send multipart in Angular. I don't think you're doing it right. Seems like you are sending JSON. – Paul Samsotha Jul 13 '21 at 22:49
  • 1
    I take back the part about not being able to use a POJO. You actually can, but the parameter will need to also be annotated with `@BeanParam`. And all the fields in the POJO will need to be annotated with `@FormDataParam("part-name")`. Also, I believe there is some issue regarding using `@Valid` with other parameter annotations (https://stackoverflow.com/a/54287707/2587435) – Paul Samsotha Jul 13 '21 at 23:03

0 Answers0