WebService大讲堂之Axis2(4):二进制文件传输2011-08-13 BlogJava 哈佛校训在《WebService大讲堂之Axis2(2):复合类型数据的传递》中讲过,如果要传递二进制文件(如图 像、音频文件等),可以使用byte[]作为数据类型进行传递,然后客户端使用RPC方式进行调用。这样做 只是其中的一种方法,除此之外,在客户端还可以使用wsdl2java命令生成相应的stub类来调用 WebService,wsdl2java命令的用法详见《WebService大讲堂之Axis2(1):用POJO实现0配置的 WebService》。WebService类中包含byte[]类型参数的方法在wsdl2java生成的stub类中对应的数据类型不再是byte[] 类型,而是javax.activation.DataHandler。DataHandler类是专门用来映射WebService二进制类型的。在WebService类中除了可以使用byte[]作为传输二进制的数据类型外,也可以使用 javax.activation.DataHandler作为数据类型。 不管是使用byte[],还是使用 javax.activation.DataHandler作为WebService方法的数据类型,使用wsdl2java命令生成的stub类中相 应方法的类型都是javax.activation.DataHandler。而象使用.net、delphi生成的stub类的相应方法类型 都是byte[]。这是由于javax.activation.DataHandler类是Java特有的,对于其他语言和技术来说,并不 认识javax.activation.DataHandler类,因此,也只有使用最原始的byte[]了。下面是一个上传二进制文件的例子,WebService类的代码如下:
package service;import java.io.InputStream;import java.io.OutputStream;import java.io.FileOutputStream;import javax.activation.DataHandler;public class FileService{ //使用byte[]类型参数上传二进制文件public boolean uploadWithByte(byte[] file, String filename){ FileOutputStream fos = null; try { fos = new FileOutputStream(filename); fos.write(file); fos.close(); } catch (Exception e) { return false; } finally { if (fos != null) { try { fos.close(); } catch (Exception e) { } } } return true;}private void writeInputStreamToFile(InputStream is, OutputStream os) throws Exception{ int n = 0; byte[] buffer = new byte[8192]; while((n = is.read(buffer)) > 0) { os.write(buffer, 0, n); }}//使用DataHandler类型参数上传文件public boolean uploadWithDataHandler(DataHandler file, String filename){ FileOutputStream fos = null; try { fos = new FileOutputStream(filename);//可通过DataHandler类的getInputStream方法读取上传数据 writeInputStreamToFile(file.getInputStream(), fos); fos.close(); } catch (Exception e) { return false; } finally { if (fos != null) { try { fos.close(); } catch (Exception e) { } } } return true;}}