via: http://hi.baidu.com/ant_boy/item/005a9b5e28047b10aaf6d7d2
用WebService传输文件,实际上就是客户端将文件先做成比特流,然后调用webservice接口,服务端再将比特流还原成文件。下面是代码:
public class FileTransferWs {
public int uploadFile(byte[] bs, String fileName){
FileOutputStream out=null ;
try {
String newFile = "C:\tmp\" + fileName;// 上传文件存放路径
out = new FileOutputStream(newFile);
try { out.write(bs); } catch (IOException e){ e.printStackTrace(); }
}catch (FileNotFoundException e) {
e.printStackTrace();
return -1;
}finally {
if(out!=null){try{ out.close(); } catch (IOException e){ e.printStackTrace(); } }
}
return 0 ;
}
}
客户端
public class FileUpload {
public static void main(String []args)throws Exception {
FileTransferWsProxy p = new FileTransferWsProxy();// 生成webservice代理对象
String filePath = " E:\Book\权证基础知识.pdf " ;
String fileName = " 权证基础知识.pdf " ;
File file = new File(filePath);
FileInputStream in = new FileInputStream(file);
byte []bs = new byte [in.available()];
in.read(bs);
in.close();
System.out.println( " 正在传输文件" " + fileName + " " " );
p.uploadFile(bs, fileName); // 调用webservice进行文件上传
System.out.println( " 文件传输完毕 " );
}
}