Problem: Storing binary data in Xml Cdata section
843834Oct 5 2004 — edited Oct 9 2004
The objective : Tranport image using xml
1. I convert the image to input stream.
2. store it in an array.
3. encode the string using Base64 library and get a string
4.then i store it in xml CDATA section.
the code snippet is
public class ImgToXml01 {
public static void main(String[] args) throws IOException
{
File inputFile = new File("C:\\Arup\\ImgXml\\read\\Sample.jpg");
FileInputStream in = new FileInputStream(inputFile);
String str="";
int c;
while ((c = in.read()) != -1) {
str+= ""+c;
}
String val = util.Base64.encode(str);
System.out.println(""+val);
OutputStream fout = new FileOutputStream("img.xml");
OutputStreamWriter out = new OutputStreamWriter(fout);
out.write("<?xml version = \"1.0\" encoding = \"ISO-8859-1\"?>\r\n");
out.write("<Image>\r\n");
out.write("[CDATA["+val+"]]");
//out.write("]]>");
out.write("</image>\r\n");
out.close();
}
}
When i retrieve it i write the code:
import org.xmldb.api.base.*;
import org.xmldb.api.modules.*;
import org.xmldb.api.*;
import org.w3c.dom.*;
import java.io.*;
import org.xml.sax.SAXException;
import oracle.xml.parser.v2.*;
public class CdataToImage01 {
public static void main(String[] args) //throws IOException
{
try{
String uri="c:\\Arup\\ImgXml\\img1.xml";
String data="";
File file = new File(uri);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fis);
DOMParser parser = new DOMParser();
parser.parse(in);
Document doc = parser.getDocument();
Node r = doc.getElementsByTagName("Image").item(0);
NodeList kids = r.getChildNodes();
if ( kids != null ) {
for ( int i = 0; i < kids.getLength(); i++ ) {
if ( (kids.item(i).getNodeType() == Node.TEXT_NODE) ||
(kids.item(i).getNodeType() == Node.CDATA_SECTION_NODE)) {
data=kids.item(i).getNodeValue();
}
}
}
String data1 = util.Base64.decode(data);
File outputFile = new File("Sample.jpg");
FileOutputStream out = new FileOutputStream(outputFile);
byte[] buff = data1.getBytes();
InputStream inn = new ByteArrayInputStream(buff);
int c;
System.out.println(buff.length);
while ((c = inn.read()) != -1) {
out.write(c);
}
inn.close();
out.close();
}
catch (SAXException e) {
System.err.println(e);
e.printStackTrace();
}
catch (Exception ex){
System.err.println("Exception occured " + ex.getMessage());
ex.printStackTrace();
}
}
}
But i am not getting the appropriate result .I get a corrupted image.
FROM
ARUP GHOSH