Create a dataHandler using the fileDataSource. Any implementation of
// javax.activation.DataSource interface can fit here.
DataHandler dataHandler = new DataHandler(fileDataSource);
String attachmentID = mc.addAttachment(dataHandler);
SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
SOAPEnvelope env = fac.getDefaultEnvelope();
OMNamespace omNs = fac.createOMNamespace(
"http://attachment.axis2.sky.org", "");
OMElement uploadFile = fac.createOMElement("uploadFile", omNs);
OMElement nameEle = fac.createOMElement("name", omNs);
nameEle.setText(destFile);
OMElement idEle = fac.createOMElement("attchmentID", omNs);
idEle.setText(attachmentID);
uploadFile.addChild(nameEle);
uploadFile.addChild(idEle);
env.getBody().addChild(uploadFile);
System.out.println("message====" + env);
mc.setEnvelope(env);
mepClient.addMessageContext(mc);
mepClient.execute(true);
MessageContext response = mepClient
.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
SOAPBody body = response.getEnvelope().getBody();
OMElement element = body.getFirstElement().getFirstChildWithName(
new QName("http://attachment.axis2.sky.org", "return"));
System.out.println(element.getText());
}
}
注意红色加粗部分的代码,由其是:
FileDataSource fileDataSource = new FileDataSource(new File(filePath));
String attachmentID = mc.addAttachment(dataHandler);
这两句就是把客户端需要上传的附件转成AttachmentId的语句,然后把这个AttachementId作为一个OMElement的类型加入到客户端的soap request中去即可:
OMElement idEle = fac.createOMElement("attchmentID", omNs);
idEle.setText(attachmentID);
uploadFile.addChild(nameEle);
uploadFile.addChild(idEle);
env.getBody().addChild(uploadFile);
来看运行效果。
客户端:
上传d:/deployment/test.jpg文件
客户端收到服务端返回的”File saved successfully”即可在服务端的” D:/upload/axis2”目录中查询是否成功上传了该文件了
可以看到,由于我们使用的是UUID因此每次上传,服务端的文件名都不会重复。
package org.sky.axis2.util;
public class UUID {
protected static int count = 0;
public static synchronized String getUUID() {
count++;
long time = System.currentTimeMillis();
String timePattern = Long.toHexString(time);
int leftBit = 14 - timePattern.length();
if (leftBit > 0) {
timePattern = "0000000000".substring(0, leftBit) + timePattern;
}
String uuid = timePattern
+ Long.toHexString(Double.doubleToLongBits(Math.random()))
+ Long.toHexString(Double.doubleToLongBits(Math.random()))
+ "000000000000000000";
uuid = uuid.substring(0, 32).toUpperCase();
return uuid;
}
}