使用axis2传输附件
程序员文章站
2022-05-21 18:40:24
...
服务端Service文件:
import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; 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; } }
服务端services.xml文件:
<service name="FS"> <description>文件服务</description> <parameter name="ServiceClass">com.liuwei.fs.FileService</parameter> <messageReceivers> <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" /> </messageReceivers> </service>
通过Axis2 code2java工具生成客户端代码FSStub和FSCallbackHandler。
以使用byte[]类型参数上传二进制文件接口uploadWithByte为例,客户端测试代码如下:
public class TestClient { public static void main(String[] args) { try { FSStub stub = new FSStub("http://localhost:8080/TestWS/services/FS"); DataHandler dh = new DataHandler(new FileDataSource("F:\\file1.txt")); UploadWithByte uwb = new UploadWithByte(); uwb.setFile(dh); uwb.setFilename("F:\\file2.txt"); FSStub.UploadWithByteResponse br = stub.uploadWithByte(uwb); System.out.println(br.get_return()); } catch (RemoteException e) { System.out.println("远程连接失败:"+e.getMessage()); e.printStackTrace(); } } }