我正在尝试使用cloudant客户端 - 2.0.0
将图像上传到cloudant数据库这是我的代码:
public static void main(String[] args) throws MalformedURLException, Exception
{
try
{
CloudantClient client = ClientBuilder.account("uri").username(user).password(password).build();
System.out.println("Server Version: " + client.serverVersion());
Database db = client.database("rss_news", false);
JSONObject obj = new JSONObject();
obj.put("_attachments", new Attachment(encodeFileToBase64Binary("C:/Users/Public/Pictures/Sample Pictures/Desert.jpg"), "image/jpeg"));
obj.put("name", "bhanwar");
db.save(obj);
}
catch (Exception e)
{
e.printStackTrace();
}
}
// A Java type that can be serialized to JSON
private static String encodeFileToBase64Binary(String fileName) throws IOException
{
File file = new File(fileName);
System.out.println(file.getName());
byte[] bytes = loadFile(file);
byte[] encoded = Base64.encodeBase64(bytes);
System.out.println(bytes.length);
String encodedString = new String(encoded);
System.out.println("---encodedString---" + encodedString);
return encodedString;
}
private static byte[] loadFile(File file) throws IOException
{
InputStream is = new FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE)
{
// File is too large
}
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)
{
offset += numRead;
}
if (offset < bytes.length)
{
throw new IOException("Could not completely read file " + file.getName());
}
is.close();
return bytes;
}
但这不起作用。
该对象在cloudant db上创建,但架构看起来不像文档中提到的“_attachments”。
此外,长度和重新启动等属性为0。
请建议。