如何把图片附件在CouchDB的Andr​​oid的? [英] How to put image attachment to CouchDB in Android?

查看:208
本文介绍了如何把图片附件在CouchDB的Andr​​oid的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的HttpClient和MIME把图像文件从Android客户端来的CouchDB。
但也有一些像这样的错误消息

I am use HttpClient and mime to put the image file from Android client to CouchDB. But there are some error message like this

D/FormReviewer(4733): {"error":"bad_request","reason":"invalid UTF-8 JSON: <<45,45,103,75,66,70,69,104,121,102,121,106,72,66,101,80,\n

这是我的code

here is my code

final String ProfileBasicID = UUID.randomUUID().toString();

Data.postImage(IconFile, "http://spark.iriscouch.com/driver/"+ProfileBasicID,new Callback<String>())


public static void postImage(File image,String url, Callback<String> success ) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPut method = new HttpPut(url);

    try {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("type", new StringBody("photo"));
        entity.addPart("form_file", new FileBody(image, "image/jpeg"));
        method.setEntity(entity);
        HttpResponse resp = httpclient.execute(method);
        Log.d("httpPost", "Login form get: " + resp.getStatusLine());
        StatusLine statusLine = resp.getStatusLine();
        Log.d(tag, statusLine.toString());
        if (entity != null) {
            entity.consumeContent();
        }
        switch(resp.getStatusLine().getStatusCode()){
        case HttpStatus.SC_CREATED:
            success.call(EntityUtils.toString(resp.getEntity()));
            break;
        default:
            throw new ClientProtocolException(statusLine.toString() +"\n"+ EntityUtils.toString(resp.getEntity()));
        }
    } catch (Exception ex) {
        Log.d("FormReviewer", "Upload failed: " + ex.getMessage() +
            " Stacktrace: " + ex.getStackTrace());
    } finally {
        // mDebugHandler.post(mFinishUpload);
        httpclient.getConnectionManager().shutdown();
    } 
}

请帮我个忙,谢谢

推荐答案

右,忘了我这里张贴pviously $ P $。
这并不像我们想象的那么简单。
一些链接我建议你阅读:

RIGHT, forget what I posted here previously. This is NOT as straightforward as we thought. Some links I suggest you read:


  1. CouchDB文档API

  2. (草案)核心API

  1. CouchDB Document API
  2. (Draft) Core API

确定。
第一个决定是,如果你想独立或内联附件。目前,我不知道亲的和反对的有,但基于您的code,和我做什么,我们会去为独立。

Ok. First decision is if you want "Standalone" or "inline attachments". Currently I don't know what the Pro's and Con's are, BUT based on your code, and what I did, we will go for "Standalone".

首先,你需要你想你的形象附加到文件的REV(改版机)的数量。按照上面的链接,这样做在该文档HEAD请求做到这一点:

Firstly, you need the rev (revision) number of the document you want to attach your image to. As per the above link, do this by doing a Head request on that doc:

private String getParentRevision(String uuid, HttpClient httpClient) {
String rev = "";
try {
    HttpHead head = new HttpHead("http://192.168.56.101/testforms/" + uuid + "/");
    HttpResponse resp = httpClient.execute(head);
    Header[] headers = resp.getAllHeaders();
    getLog().debug("Dumping headers from head request");;
    for (Header header : headers) {
    getLog().debug(header.getName() + "=" + header.getValue());
    if ("Etag".equals(header.getName())) {
        StringBuilder arg = new StringBuilder(header.getValue());
        if (arg.charAt(0) == '"') {
        arg.delete(0, 1);
        }
        if (arg.charAt(arg.length()-1) == '"'){
        arg.delete(arg.length()-1, arg.length());
        }
        rev = arg.toString();
        break;
    }
    }

} catch (Exception ex) {
    getLog().error("Failed to obtain DOC REV!", ex);
}

return rev;
}

我appologise的硬编码等,我正在学习和实验在这里;)
在参数uuid是目标文件的UUID。
注意去除包装'字符的时候,我们得到的eTag(是的,ETag头是版本号)。

I appologise for the hardcoding etc, I'm learning and experimenting here ;) The "uuid" parameter is the UUID of the target document. Note the removal of the wrapping '"' characters when we got the Etag (yes, the Etag header is the revision number).

那么,当我们得到了,我们实际上可以发送图像:

THEN, when we got that, we can actually send the image:

String serveURL = "http://192.168.56.101/testforms/" + data.getString(PARENT_UUID) + "/" + imgUuid;

if (docRev != null && !docRev.trim().isEmpty()) {
    //This is dumb...
    serveURL += "?rev=" + docRev + "&_rev=" + docRev;
}
HttpPut post = new HttpPut(serveURL);
    ByteArrayEntity entity = new ByteArrayEntity(imageData);
entity.setContentType(data.getString(MIME_TYPE));;

post.setEntity(entity);

    HttpResponse formServResp = httpClient.execute(post);

有了这个,我能够武官图片到我的文档;)

With this, I was able to attache images to my docs ;)

正如前面提到的,请注意,我也是新CouchDB的,所以可能有更简单的方法来做到这一点!

As mentioned, please be aware that I'm also new to CouchDB, so there might be simpler ways to do this!

东西我刚才发现(但应更早已经发现)是有一个竞争条件的潜力在这里,如果,例如,多个客户端试图画面同步连接到同一个文件。其原因是,转速值与每个换向文档改变。
在这种情况下,你会得到从服务器像

Something I just discovered now (but should have spotted earlier) is that there is the potential of a race condition here, if, for example, multiple clients are trying to attach images to the same document simultaneously. The reason is that the rev value changes with each change to the document. In such a case, you will get a reply from the server like

{"error":"conflict","reason":"Document update conflict."}

最简单的解决方法就是在这样的情况下重试,直到它的工作原理,或直到一个自我施加的误差极限被击中...

Easiest solution is to just retry in such a case, until it works, or until a self imposed error limit is hit...

干杯!

这篇关于如何把图片附件在CouchDB的Andr​​oid的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆