java端:写一个名为ZhuaTuSerlvet的Serlvet,这个类需要用到flex-messaging-core.jar这个包.
需要用到SerializationContext,ASObjectAmf3Input,Amf3Output这几个类(
import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.ASObject;
import flex.messaging.io.amf.Amf3Input;
import flex.messaging.io.amf.Amf3Output;
)
其中doPost方法的内容如下:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Amf3Input amf3in = new Amf3Input(context);
Amf3Output amf3out = new Amf3Output(context);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
amf3in.setInputStream(new DataInputStream(request.getInputStream()));
String uploadPath = "c:/";
response.setContentType("application/octet-stream");
InputStream is = request.getInputStream();
try {
int size = 0;
byte[] b = new byte[100000];
byte[] tmp = new byte[100000];
int len = 0;
long time = System.currentTimeMillis();
File file = new File(uploadPath + time + ".png");
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
while ((len = is.read(tmp)) != -1) {
dos.write(tmp, 0, len);
size += len;
}
dos.flush();
dos.close();
//System.out.println("图片的保存路径是: " + file.getAbsolutePath());
//返回文件保存路径
ASObject message1 = new ASObject();
//像HashMap一样设置变量
message1.put("path", file.getAbsolutePath());
amf3out.setOutputStream(stream);
amf3out.writeObject(message1);
amf3out.flush();
response.getOutputStream().write(stream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
}
flex端:
/**
* 上传图片到服务器
*/
public function uploadFile():void{
var request:URLRequest = new URLRequest("http://192.168.3.139:8989/1test/servlet/ZhuaTuSerlvet");
loader = new URLLoader();
request.method=URLRequestMethod.POST;
request.contentType = "application/octet-stream";
request.data = new JPEGEncoder(85).encode(imgBD);
//以二进制形式通信.不加此行会报空指针异常
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.load(request);
loader.addEventListener(Event.COMPLETE,onComplete);
//loader.addEventListener(IOErrorEvent.IO_ERROR,onError);
//loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurityError);
}
/**
* 上传成功
*/
public function onComplete(event:Event):void{
switch(event.type){
case Event.COMPLETE:
var bytes:ByteArray = loader.data as ByteArray;
var obj:Object = bytes.readObject();
//遍历所有参数
//for(var key:* in obj){
//Alert.show(key+":"+obj[key]);
//}
Alert.show("上传成功,图片保存在 " + obj["path"]);
break;
}
}
开源组件:http://code.google.com/p/flexupload/
Sample:http://www.chaosm.net/blog/2011/08/14/upload-multiple-files-in-adobe-air-with-zend-amf-and-flex/