Tuesday, May 25, 2010

base64 encoding for attachments in a web service

Attachments can be sent over web services through base64 encoding of the binary files and transporting them as string through a SOAP message.

Here is util file in java for encoding and decoding a binary file into base64 string.

package com.peoplesoft.hr.sa;
import java.util.zip.*;
import java.util.Enumeration;
import java.io.*;
import java.util.Stack;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

public class base64Utils {
public base64Utils() {
}

/**
* encodes a file in base64 format
* @param filename name of the file to encode
* @return String the base64 text of the encoded file
*/
public String base64Encode(String filename) {
BASE64Encoder b64e = new BASE64Encoder();
byte[] temparray, filearray;
int bytecount;
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
filename));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
b64e.encode(bis, bos);
bis.close();
return bos.toString();
}
catch (Exception a) {
return null;
}
}

/**
* decodes a file from base64 format
* @param filename name of the file to decode to
* @param filedata the base64 encoded data
* @return String the base64 text of the encoded file
*/

public boolean base64Decode(String filename, String filedata)
{
BASE64Decoder b64d=new BASE64Decoder();
byte [] outputfile;
try {
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(filename));
outputfile=b64d.decodeBuffer(filedata);
bos.write(outputfile);
bos.close();
}
catch (Exception a) {
return false;
}
return true;
}
}

No comments:

Post a Comment