Java - read message/rfc822 from MultipartFormDataInput

Viewed 231

I have a form for file upload

<form id="mydropzone" class="dropzone" style="min-height: 100px" action="/files/uploadFile"  method="POST" enctype="multipart/form-data">
        <input type="hidden" name="noteId" th:value="${model.id}" />
</form>

MultipartFormDataInput. comes from javax.ws.rs.core.GenericType

    @POST
    @Consumes(value = MediaType.MULTIPART_FORM_DATA)
    @Path("/uploadFile")
    @AllowPermission(value = Permission.EDIT_NOTE)
    public Response uploadFileMultipart(MultipartFormDataInput input)
            throws RequestException, IOException {
        System.out.println("theInput " + input);
        FileModel model = convertToFile(input, "file");
        Long noteId = getOptionalParam(input, "noteId");
        model.setNoteId(noteId);
        UploadFileMutation.UploadFile uploadFile = fileService.uploadFile(model);
        if(uploadFile != null){
            return Response.ok(uploadFile).build();
        }else {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }

    }

the problem come from here inputPart.getBody(InputStream.class, null) it always return null

private FileModel convertToFile(MultipartFormDataInput input,
            String paramName) throws IOException {
        Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
        List<InputPart> inputParts = uploadForm.get(paramName);

        for (InputPart inputPart : inputParts) {

            MultivaluedMap<String, String> header = inputPart.getHeaders();
            String fileName = getFileName(header);

            //convert the uploaded file to inputstream
            InputStream inputStream = inputPart.getBody(InputStream.class, null);

            byte[] bytes = IOUtils.toByteArray(inputStream);
            FileModel model = new FileModel();
            model.setName(fileName);
            model.setData(bytes);
            return model;
        }
        return null;
    }

Note this code works just fine with all types except content-type : message/rfc822

any hint on how I can convert .eml files to byte[]

I tried this method but I got the same error

private byte[] readByteArray(InputPart inputPart) throws Exception {
        Field f = inputPart.getClass().getDeclaredField("bodyPart");
        f.setAccessible(true);
        BodyPart bodyPart = (BodyPart) f.get(inputPart);
        SingleBody body = (SingleBody)bodyPart.getBody();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        body.writeTo(os);
        byte[] fileBytes = os.toByteArray();
        return fileBytes;
    }
0 Answers
Related