[英]Convert blob to string to to create a json object and then change the string back to blob
My requirement is to convert the blob in a database field to string to create a json object. 我的要求是将数据库字段中的Blob转换为字符串以创建json对象。 I have achieved that. 我已经做到了。
Now, I need to convert this string back to blob. 现在,我需要将此字符串转换回blob。 I wrote the below code. 我写了下面的代码。 But, it does not work. 但是,它不起作用。 In my instance, I have the word document stored as blob. 就我而言,我将文档文档存储为blob。 I converted it to string but when I converted the string to blob, the document does not open properly. 我将其转换为字符串,但是当我将字符串转换为blob时,文档无法正确打开。
Please let me know a way to convert the string back to blob. 请让我知道一种将字符串转换回blob的方法。
DocumentTemplateKey documentTemplateKey = new DocumentTemplateKey();
documentTemplateKey.documentTemplateID = "XX";
DocumentTemplateDtls documentTemplateDtls = DocumentTemplateFactory.newInstance().read(documentTemplateKey);
byte[] blobAsBytes = documentTemplateDtls.contents.copyBytes();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(blobAsBytes, 0, blobAsBytes.length);
String pdfBase64String =
org.apache.commons.codec.binary.StringUtils.newStringUtf8(org.apache.
commons.codec.binary.Base64.encodeBase64(bos.toByteArray()));
OutputStreamWriter out = new OutputStreamWriter(System.out);
JsonWriter writer = new JsonWriter(out);
//set indentation for pretty print
writer.setIndent("\t");
//start writing
writer.beginObject(); //{
writer.name("blob").value(pdfBase64String);
byte[] stringAsBytes = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(pdfBase64String);
Blob blob = new Blob(stringAsBytes);
documentTemplateDtls.contents = blob;
documentTemplateDtls.documentTemplateID = "XX12";
documentTemplateDtls.name = "XX12";
DocumentTemplateFactory.newInstance().insert(documentTemplateDtls);
writer.endObject();
writer.flush();
//close writer
writer.close();
Here's your problem: 这是您的问题:
byte[] stringAsBytes = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(pdfBase64String);
You're getting the bytes of your base64 string, but you ought to be putting it through a base64 decoder. 您正在获取base64字符串的字节,但应将其通过base64解码器进行处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.