cloudant / java-cloudant

A Java client for Cloudant
Apache License 2.0
79 stars 68 forks source link

save image file or audio file as attachment to cloudant #329

Closed zeevmindali closed 7 years ago

zeevmindali commented 7 years ago

Dear all,

i using the latest client to cloudant. i want to add attachment (can be image file of jpg,png or audio file 3gp). is there an example how to use it with android studio or java?

zeev

rhyshort commented 7 years ago

The attachments documentation has some examples, but the gist is use the Database#saveAttachment method to upload the attachment separately to the document or save the attachment inline with the document like:

Attachment attachment = new Attachment();
attachment.setData(Base64.encodeBase64String("attachment test string".getBytes()));
attachment.setContentType("text/plain");
Foo foo = new Foo(); // Foo extends Document
foo.addAttachment("attachment.txt", attachment);
db.save(foo);

Based on the file types you using, it would probably be best to upload the attachment separately to the document.

zeevmindali commented 7 years ago

o.k. , i got to upload the image , using inputStream. how i can get an url address to my attachment?

rhyshort commented 7 years ago

The byte stream passed to the saveAttachment method is read by the server and the attachment is stored in the Cloudant database if the request completes successfully. There is no save for the database.

The three argument version of saveAttachment creates a new document which only contains the attachments. The 5 argument version will create a new revision of an existing document which contains all the data of the previous revision with the attachment added.

When receiving the document from the server the attachment content is not included by default. To access the attachment for the document you provided you would go to https://<accountName>.cloudant.com/<dbName>/2fc4491105de4e929273ddfa878c49c4/thumb

rhyshort commented 7 years ago

For standalone access to the attachment using the client:

InputStream in;
try {
   HttpConnection conn = Http.GET(new URL(db.getDBUri() + "/2fc4491105de4e929273ddfa878c49c4" + "/thumb"));
   in = client.executeRequest(conn).responseAsInputStream();
} catch (CouchException e) {
   // handle exception
} catch (MalformedURLException e){
   // handle exception
} finally {
   in.close();
}
zeevmindali commented 7 years ago

thank you a lot, finally, working like a charm, with the fastest responses that i ever had. this is why each day i say "IBM is the right choice"

Keep up the good work, and thanks a lot.

rhyshort commented 7 years ago

Great glad you've got it working.