Search code examples
javaosgiaemjcr

How to convert byte[] to Binary to set jcr:data with file contents?


I am trying to save binary data (image) into a JCR node. I'm fetching an image from an evernote Note using this method: public byte[] getBody() and then trying to set property jcr:data with the contents of the file using setProperty(string, Binary)

This is how I'm doing this:

Node n; 
byte [] fileContent = resrouce.getData().getBody();
....
n.setProperty("jcr:mimeType", "image/png");
n.setProperty("jcr:data", fileContent);

However, I get an error that

no suitable method found for setProperty(java.lang.String,byte[])

What is a way to set jcr:data property with file contents that are in binary?


Solution

  • You can use the ValueFactory to convert the InputStream to a Binary value. The ValueFactory can be got from the Session object.

    ValueFactory factory = session.getValueFactory();
    InputStream is = new ByteArrayInputStream(fileContent);
    
    Binary binary = factory.createBinary(is);
    Value value = factory.createValue(binary);
    n.setProperty("jcr:data", value);
    

    To learn more about writing to the repository, refer to this specification.