Image upload to cosmosdb not working(java sdkv2)

Viewed 28

I am trying to upload a sample .png file to cosmosdb but facing some issues. I am using AsyncDocumentClient class to create an attachment.

Inputstream is a .png file in resources folder. Document creation works fine and I am getting the document id back and it is inserted to locally runnning cosmosdb emulator. The issues comes when I try to insert an img file

Method used:

createAttachment(String documentLink, InputStream mediaStream, MediaOptions options, RequestOptions requestOptions)

AsyncDocumentClient clien.....

 var createdDocument = client.createDocument(getCollectionNameLink(databaseId, collectionId), getDocumentDefinition(), null, false)
                .toBlocking().single().getResource();

RequestOptions options = new RequestOptions();
options.setPartitionKey(new PartitionKey(createdDocument.getId()));//partition ket is the same as ID

System.out.println("document id:"+createdDocument.getId()); //works


        try(InputStream stream= getMedia1Stream()){
            MediaOptions mediaOptions=new MediaOptions();
            mediaOptions.setContentType("application/octet-stream");
            Attachment createdAttachment = client.createAttachment(createdDocument.getSelfLink(), stream, mediaOptions, options)
                    .toBlocking().single().getResource();

            System.out.println("attachment id:"+createdAttachment.getId()); // throws NullPointer because createdAttachment is null

        }catch (Exception e) {
            e.printStackTrace();
        }





Helper methods:
    private InputStream getMedia1Stream()
    {
        return this.getClass().getResourceAsStream("/img.png");
    }

    private static Document getDocumentDefinition() {
        String uuid = UUID.randomUUID().toString();
        Document doc = new Document(String.format("{ "
                        + "\"id\": \"%s\", "
                        + "\"partitionkey\": \"%s\", "
                        + "\"sgmts\": [[6519456, 1471916863], [2498434, 1455671440]]"
                        + "}"
                , uuid, uuid));
        return doc;
    }
0 Answers
Related