Tuesday, April 22, 2014

Add a attachment to CouchDB with play framework JavaAPI

I tired to write a rest API which act as a mediator between clients and CouchDB API. This was done using Playframework's Java API. I wrote the following controller method which takes a POST request which contains file name, content-type and file to be stored as parameters and send as a PUT request to CouchDB.


   public static Result putAttachment(){
        Http.MultipartFormData body = request().body().asMultipartFormData();
        Http.MultipartFormData.FilePart picture = body.getFile("picture");
        String fileName=null;
        String contentType=null;
        File file=null;
        if (picture != null) {
            fileName = picture.getFilename();
            contentType = picture.getContentType();
            file = picture.getFile();
        } else {
            //TODO implement
        }
        String restServiceUrl = "http://127.0.0.1:5984/test/a/"+fileName;
        F.Promise<play.libs.WS.Response> future =play.libs.WS.url(restServiceUrl)
                .setContentType(contentType).setQueryParameter("rev","7-00e01f7f430649d984fc8488358a1953")
                .put(file);
        return Results.ok(future.get(50000000).getBody());
    }

No comments:

Post a Comment