Search code examples
javaserializationcxfdeserializationmultipart

How to convert Attachment Object to ByteArray in JAVA


I am writing a web service in JAVA using Apache CXF.

So, I have a method whose prototype is following:

public Response upload(@Multipart("id") int Id, 
            @Multipart("file") Attachment attachment) {

Now, I want to convert this attachment to byte[] . How can I do it?


Solution

  • Here is how you can read the content of the attachment and store it inside a byte array. Alternatively you can write directly to an OutputStream and skip the conversion to byte[].

            DataHandler dataHandler = attachment.getDataHandler();
            final byte[] data;
            try (InputStream inputStream = dataHandler.getInputStream()) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                final byte[] buffer = new byte[4096];
                for (int read = inputStream.read(buffer); read > 0; read = inputStream.read(buffer)) {
                    outputStream.write(buffer, 0, read);
                }
                data = outputStream.toByteArray();
            }
    
            //todo write data to BLOB
    

    If you want to be more memory efficient or if the attachment does not fit into memory, you can write directly to the blob's output stream. Just replace the ByteArrayOutputStream with OutputStream outputStream = blob.setBinaryStream(1);