android - 如何将图像附件放入 Android 中的 CouchDB?

标签 android image couchdb httpclient attachment

我正在使用 HttpClient 和 mime 将图像文件从 Android 客户端放到 CouchDB。 但是有一些这样的错误信息

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

这是我的代码

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();
    } 
}

请帮帮我,谢谢

最佳答案

对了,忘记我之前在这里发布的内容。 这并不像我们想象的那么简单。 我建议您阅读一些链接:

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

好的。 第一个决定是您想要“独立”还是“内联附件”。目前我不知道优点和缺点是什么,但根据您的代码和我所做的,我们将选择“独立”。

首先,您需要要将图像附加到的文档的修订(修订)号。按照上面的链接,通过对该文档执行 Head 请求来执行此操作:

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;
}

我对硬编码等感到抱歉,我正在这里学习和试验 ;) “uuid”参数是目标文档的 UUID。 请注意,当我们获得 Etag 时,删除了环绕的“”字符(是的,Etag header 是修订号)。

然后,当我们得到它时,我们实际上可以发送图像:

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);

有了这个,我就可以将图像附加到我的文档中了;)

如前所述,请注意我也是 CouchDB 的新手,因此可能有更简单的方法来做到这一点!

我现在刚刚发现(但应该早点发现)的是,这里可能存在竞争条件,例如,如果多个客户端同时尝试将图像附加到同一个文档。原因是 rev 值随着文档的每次更改而更改。 在这种情况下,您会从服务器得到回复,如

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

最简单的解决方案是在这种情况下重试,直到它起作用,或者直到达到 self 施加的错误限制...

干杯!

关于android - 如何将图像附件放入 Android 中的 CouchDB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9852809/

相关文章:

html - 在 HTML 页面上使用 CSS Sprite

hadoop - 如何在 CouchDB 中实现分布式事务?

JavaScript,if语句总是只执行 'else'分支

ruby - 如何停止思考 "relationally"

java - JSON键一些时间字符串和一些时间列表值android改造

android - 恢复数据放入 JSONObject 的顺序

javax.imageio.ImageIO 在灰度图像上读取不正确的 RGB 值

android - 使用点击上下文菜单选项打开上下文菜单

android - 动画没有按预期工作

c++ - Pixbuf 显示有关图像的错误信息