0

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?

2
  • Do you wan to read the content of the attachemt to a byte array, or you want to serialize it ? Please clarify your question because it;s unclear what you are asking Commented Sep 20, 2016 at 18:35
  • Finally , I have to store it as a BLOB in the database. Commented Sep 20, 2016 at 18:37

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.