private function DetectPhoto(e:MouseEvent):void{
var requestUrl:String = "POST URL";
_request = new URLRequest(requestUrl);
_request.method = URLRequestMethod.POST;
var _params:Object = new Object();
_params.api_key = this.appKey; //应用的api的key
_params.api_secret = this.appSecret;
_params.image = _photo; // 注意这里,一般API要求的参数名称,比如API要求post的图片参数是image,这个地方就写_params.image
_params.fileName = "img";
var fileData:Object = extractFileData(_params);
_request.data = createUploadFileRequest(fileData, _params).getPostData();
_urlLoader = new URLLoader();
_urlLoader.addEventListener(Event.COMPLETE, completeHeadHandler);
_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, urlIOErrorHandler);
try{
_urlLoader.load(_request);
} catch (error:ArgumentError) {
trace("参数错误");
} catch (error:SecurityError) {
trace("发生安全错误");
}
}
protected function extractFileData(values:Object):Object {
if (values == null) { return null; }
//Check to see if there is a file we can upload.
var fileData:Object;
if (isValueFile(values)) {
fileData = values;
} else if (values != null) {
for (var n:String in values) {
if (isValueFile(values[n])) {
fileData = values[n];
delete values[n];
break;
}
}
}
return fileData;
}
protected function isValueFile(value:Object):Boolean {
return (value is FileReference || value is Bitmap || value is BitmapData || value is ByteArray);
}
protected function createUploadFileRequest(fileData:Object, values:Object = null):PostRequest {
var post:PostRequest = new PostRequest();
//Write the primitive values first, if they exist
if (values) {
for (var n:String in values) {
post.writePostData(n, values[n]);
}
}
//If we have a Bitmap, extract its BitmapData for upload.
if (fileData is Bitmap) {
fileData = (fileData as Bitmap).bitmapData;
}
if (fileData is ByteArray) {
//If we have a ByteArray, upload as is.
post.writeFileData(values.fileName,
fileData as ByteArray,
values.contentType
);
} else if (fileData is BitmapData) {
//If we have a BitmapData, create a ByteArray, then upload.
var ba:ByteArray = PNGEncoder.encode(fileData as BitmapData);//PNGEncoder在Adobe的包里有
post.writeFileData(values.fileName, ba, 'image/png');
}
post.close();
_request.contentType =
'multipart/form-data; boundary='
+ post.boundary;
return post;
}
protected var urlRequest:URLRequest;
private function completeHeadHandler(evt:Event):void {
_urlLoader.removeEventListener(Event.COMPLETE, completeHeadHandler);
_urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, urlIOErrorHandler);
_data = (evt.target as URLLoader).data;// 返回的数据
<span style="white-space:pre"> </span>}
}
AS3 POST二进制图片到服务器
最新推荐文章于 2021-03-12 18:35:57 发布