couchdb通过httpclient上传图像

cngwdvgl  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(355)

我用 couchdb ,我尝试将图像上载到 couchdb 具有此功能的文档:

public JSONObject uploadPicture(PutAttachment putAttachment) {
    JSONObject obj = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPut httpPut = new HttpPut(baseUrl() + putAttachment.getDbName() + "/" + putAttachment.getDocName() + "/attachment?rev=" + putAttachment.getRev());

        ByteArrayEntity img = new ByteArrayEntity(putAttachment.getByteImg());
        httpPut.setEntity(img);

        httpPut.setHeader("Content-Length", "" + (int) img.getContentLength());
        httpPut.setHeader("Content-type", "image/png");
        httpPut.setHeader(authenticate());
        HttpResponse response;

        response = httpclient.execute(httpPut);

        HttpEntity entity = response.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            obj = new JSONObject(convertStreamToString(instream));
            instream.close();
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return obj;

}

我不知道为什么但是每次我 ClientProtocolException 之后

httpclient.execute(httpPut).

有人知道吗

uwopmtnx

uwopmtnx1#

我今天一直在挣扎。在研究了这个之后:如何在android中把图片附件放到couchdb上?
最后我得到了这样的结果:

public static HttpResponse makeUpdateRequest(String uri, Bitmap bmp) {
    try {
        HttpPut httpPut = new HttpPut(uri);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 0, stream);
        ByteArrayEntity entity = new ByteArrayEntity(stream.toByteArray());
        entity.setContentType("image/png");
        entity.setChunked(true);
        httpPut.setEntity(entity);
        return new DefaultHttpClient().execute(httpPut);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

用地板的方式称之为:

HttpResponse updateResponse = makeUpdateRequest(
            AppConfig.WEB_SERVER_DB_URI + uuid + 
            "/attachment?rev=" + revId, bmp);

这是一本很好的读物:http://wiki.apache.org/couchdb/http_document_api#inline_attachments

相关问题