使用axis2传输附件

服务端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();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值