这里的三种方式分别为:
1、二进制传输(BINARY)
2、字符串传输(String)
3、文件流上传(File)
开发IDE:FlashDevelop、Zend Studio。
1)设置FlashDevelop使用flash player10(debug版本,因为有一个demo使用了本地预览)
“工具”菜单 –》 “软件设置”(快捷键F10)—》 点击左侧的“AS3Context”,在Language中的“Default Flash Version”修改为10,选择Player Debug 的路径
2、因为在flashDevelop中使用到了fl组件,所以需要先下载fl.swc,可以在google code上下载的到,下载链接地址>> (关于在flashdevelop中如何使用swc,可以gg一下)
3、使用到了Adobe的官方组件PNGEncoder,google code上的下载地址>>
4、使用到了as3的base64Encode,google code上的链接地址>>
一、使用二进制上传图片
完整的as3代码:
package
{
import com.adobe.images.JPGEncoder;
import com.adobe.images.PNGEncoder;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import fl.controls.Button;
import flash.events.MouseEvent;
import flash.filters.GlowFilter;
import flash.net.*;
import flash.filters.BitmapFilterQuality;
import flash.utils.ByteArray;
/**
* ...
* @author ZhangYi
*/
public class Main extends Sprite
{
private var _base:Shape;
private var _btn:Button;
private var _loader:Loader;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
inited();
}
private function inited():void {
var mc:MovieClip = new MovieClip();
mc.graphics.beginFill(0x000000, 0.2);
mc.graphics.drawRect(0, 0, 320, 455);
mc.x = 30;
mc.y = 60;
addChild(mc);
_loader = new Loader();
_loader.load(new URLRequest("../assets/1.png"));
mc.addChild(_loader);
_loader.addEventListener(MouseEvent.ROLL_OVER, addFilterHandler);
_loader.addEventListener(MouseEvent.ROLL_OUT, removeFilterHandler);
_btn = new Button();
_btn.label = "截图";
_btn.x = 30;
_btn.y = 30;
addChild(_btn);
_btn.addEventListener(MouseEvent.CLICK, clickHandler);
}
private function clickHandler(evt:MouseEvent):void {
var bitmapData:BitmapData = new BitmapData(_loader.width, _loader.height, true, 0);
bitmapData.draw(_loader);
//var encoder:JPGEncoder = new JPGEncoder(100);
//var bytes:ByteArray = encoder.encode(bitmapData);
var bytes:ByteArray = PNGEncoder.encode(bitmapData);
var req:URLRequest = new URLRequest("http://meteoric.com/test/uploadFile/upload_1.php");
req.data = bytes;
req.method = URLRequestMethod.POST;
req.contentType = "application/octet-stream";
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.load(req);
loader.addEventListener(Event.COMPLETE, completeHandler);
}
private function completeHandler(evt:Event):void {
trace(evt.target.data);
}
private function addFilterHandler(evt:MouseEvent):void {
var filtersArr:Array = new Array();
filtersArr = _loader.filters;
filtersArr.push(getBitmapFilter());
_loader.filters = filtersArr;
}
private function removeFilterHandler(evt:MouseEvent):void {
_loader.filters = null;
}
private function getBitmapFilter():GlowFilter {
var color:Number = 0xFF0000;
var alpha:Number = 1;
var blurX:Number = 5;
var blurY:Number = 5;
var strength:Number = 4;
var inner:Boolean = false;
var knockout:Boolean = false;
var quality:Number = BitmapFilterQuality.LOW;
return new GlowFilter(color, alpha, blurX, blurY, strength, quality, inner, knockout);
}
}
}
后台php的代码:
<?php
$filename="teststream.jpg";//要生成的图片名字
$xmlstr = $GLOBALS[HTTP_RAW_POST_DATA];
if(empty($xmlstr)) {
$xmlstr = file_get_contents('php://input');
}
$jpg = $xmlstr;//得到post过来的二进制原始数据
$file = fopen("image/".$filename,"w");//打开文件准备写入
fwrite($file,$jpg);//写入
fclose($file);//关闭
echo "ok~~~";
?>
运行后,可以在相应的目录中看到图片已经上传成功了,如下图所示:
以下说明转载至<as3传byteArray,php接二进制文件>
PHP默认只识别application/x-www.form-urlencoded标准的数据类型。
因此,对型如text/xml 或者 soap 或者 application/octet-stream 之类的内容无法解析,如果用$_POST数组来接收就会失败!
故保留原型,交给$GLOBALS['HTTP_RAW_POST_DATA'] 来接收。
另外还有一项 php://input 也可以实现此这个功能
php://input 允许读取 POST 的原始数据。和 $HTTP_RAW_POST_DATA 比起来,它给内存带来的压力较小,并且不需要任何特殊的 php.ini 设置。php://input和 $HTTP_RAW_POST_DATA 不能用于 enctype=”multipart/form-data”。’
而在前台则使用JPGEncoder或是PNGEncoder将BitmapData转成二进制,使用post传给php
二、使用字符串提交(采用Base64编码)
as3代码:
package
{
import com.adobe.images.JPGEncoder;
import com.adobe.images.PNGEncoder;
import com.hurlant.util.Base64;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import fl.controls.Button;
import flash.events.MouseEvent;
import flash.filters.GlowFilter;
import flash.net.*;
import flash.filters.BitmapFilterQuality;
import flash.utils.ByteArray;
/**
* ...
* @author ZhangYi
*/
public class Base64Test extends Sprite
{
private var _base:Shape;
private var _btn:Button;
private var _loader:Loader;
public function Base64Test()
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
inited();
}
private function inited():void {
var mc:MovieClip = new MovieClip();
mc.graphics.beginFill(0x000000, 0.2);
mc.graphics.drawRect(0, 0, 320, 455);
mc.x = 30;
mc.y = 60;
addChild(mc);
_loader = new Loader();
_loader.load(new URLRequest("../assets/1.png"));
mc.addChild(_loader);
_loader.addEventListener(MouseEvent.ROLL_OVER, addFilterHandler);
_loader.addEventListener(MouseEvent.ROLL_OUT, removeFilterHandler);
_btn = new Button();
_btn.label = "截图";
_btn.x = 30;
_btn.y = 30;
addChild(_btn);
_btn.addEventListener(MouseEvent.CLICK, clickHandler);
}
private function clickHandler(evt:MouseEvent):void {
addFilterHandler();
var bitmapData:BitmapData = new BitmapData(_loader.width, _loader.height, true, 0);
bitmapData.draw(_loader);
var bytes:ByteArray = PNGEncoder.encode(bitmapData);
var pngString:String = Base64.encodeByteArray(bytes);
var variables:URLVariables = new URLVariables();
variables.png = pngString;
variables.name = "photo002";
var req:URLRequest = new URLRequest("http://meteoric.com/test/uploadFile/upload_2.php");
req.data = variables;
req.method = URLRequestMethod.POST;
var urlloader:URLLoader = new URLLoader();
urlloader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlloader.addEventListener(Event.COMPLETE, completeHandler);
urlloader.load(req);
trace(pngString);
}
private function completeHandler(evt:Event):void {
trace(evt.target.data);
}
private function addFilterHandler(evt:MouseEvent=null):void {
var filtersArr:Array = new Array();
filtersArr = _loader.filters;
filtersArr.push(getBitmapFilter());
_loader.filters = filtersArr;
}
private function removeFilterHandler(evt:MouseEvent):void {
_loader.filters = null;
}
private function getBitmapFilter():GlowFilter {
var color:Number = 0xFF0000;
var alpha:Number = 1;
var blurX:Number = 5;
var blurY:Number = 5;
var strength:Number = 4;
var inner:Boolean = false;
var knockout:Boolean = false;
var quality:Number = BitmapFilterQuality.LOW;
return new GlowFilter(color, alpha, blurX, blurY, strength, quality, inner, knockout);
}
}
}
后台php代码:
<?php
function base64_to_png($inputfile, $outputfile ) {
$imageData = $inputfile;
$file = fopen( $outputfile, "w" );
fwrite( $file, base64_decode( $imageData ) );
fclose($file);
}
base64_to_png("".$_POST['png'], "image/". $_POST["name"] . ".png");
print "info=ok!!";
?>
控制台上可以看到将bitmapdata转为字符串的结果:
后台保存得到的图片:
三、使用FileReference类进行上传
as3代码:
package
{
import fl.controls.Button;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.BevelFilter;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.net.URLRequest;
import flash.utils.ByteArray;
/**
* ...
* @author ZhangYi
*/
public class FileReferenceUpload extends Sprite
{
private var _btn:Button;
private var _fileRef:FileReference;
private var _loader:Loader;
public function FileReferenceUpload()
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
inited();
}
private function inited():void {
_btn = new Button();
_btn.label = "选择图片";
_btn.x = 100;
_btn.y = 100;
addChild(_btn);
_btn.addEventListener(MouseEvent.CLICK, clickHandler);
_loader = new Loader();
_loader.x = 100;
_loader.y = 150;
addChild(_loader);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, resizeImage);
}
private function resizeImage(evt:Event):void {
var size:uint = 300;
var w:Number = _loader.width;
var h:Number = _loader.height;
var scale:Number = w / h;
if (w > h) {
_loader.width = size;
_loader.height = size / scale;
} else if (h > w) {
_loader.height = size;
_loader.width = size * scale;
} else {
_loader.height = _loader.width = size;
}
var req:URLRequest = new URLRequest("http://meteoric.com/test/uploadFile/upload_3.php");
_fileRef.upload(req);
}
private function getImageFilter():FileFilter {
return new FileFilter("支持的图片类型(*.jpg;*.jpeg;*.gif;*.png)", "*.jpg;*.jpeg;*.gif;*.png");
}
private function getFilterTypes():Array {
return [
getImageFilter(),
new FileFilter("GIF 文件 (*.gif)", "*.gif"),
new FileFilter("PNG 文件 (*.png)", "*.png"),
new FileFilter("JPG 文件 (*.jpg)", "*.jpg;*.jpeg")
];
}
private function clickHandler(evt:MouseEvent):void {
_fileRef = null;
_fileRef = new FileReference();
_fileRef.addEventListener(Event.SELECT, selectHandler, false, 0, true);
_fileRef.addEventListener(Event.COMPLETE, onloadedHandler, false, 0, true);
_fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadImageCompleteHandler, false, 0, true);
_fileRef.browse(getFilterTypes());
}
private function selectHandler(evt:Event):void {
_fileRef.removeEventListener(Event.SELECT, selectHandler);
_fileRef.load();
}
private function onloadedHandler(evt:Event):void {
_fileRef.removeEventListener(Event.COMPLETE, onloadedHandler);
_loader.loadBytes(_fileRef.data);
}
private function uploadImageCompleteHandler(evt:DataEvent):void {
trace(evt.data);
_fileRef.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadImageCompleteHandler);
_fileRef = null;
}
}
}
后台php代码:
<?php
if ($_FILES ["Filedata"] ["error"] > 0) {
exit("Error: " . $_FILES ["Filedata"]["error"]);
}
$fileName = iconv("utf-8","gb2312", $_FILES ["Filedata"]["name"]);
$reallyName = "image/".$fileName;
if (file_exists ($reallyName)) {
unlink($reallyName);
}
if (!is_dir("upload")) {
mkdir("upload");
}
move_uploaded_file( $_FILES ["Filedata"]["tmp_name"], $reallyName);
echo "Stored in: " . "image/" . $fileName;
?>
以上三种方式,在不同的场景下面可能应用不太一样,比如第二种,使用编码后的字符串方式进行传输的,这样就可以通过socket通道传输数据了(虽然这很浪费而且耗费带宽,环境允许的话还是应该优先考虑使用web接口进行处理)。针对不同的上传方式,后台处理各不一样,可以看到上面的三个php写的都不一样。
在Flex中,可以使用内置的一些类、方法将bitmapdata转化为字符串,在线例子:converting-an-imagesnapshot-object-into-a-base-64-encoded-string-in-flex-3
用到的类也比较简单(ImageSnapshot中的encodeImageAsBase64、captureImage):
private function getBase64StringFromBody():String
{
var _matrix:Matrix = new Matrix(1,0,0,1,0,0);
_matrix.scale(1,1);
var bitmapData:BitmapData = new BitmapData(320,455,true,0);
bitmapData.draw(photoEditContainer, _matrix);
var bt:Bitmap = new Bitmap(bitmapData,"auto",true);
var tempCan:Canvas = new Canvas();
tempCan.rawChildren.addChild(bt);
_matrix = new Matrix(1,0,0,1,0,0);
bitmapData = new BitmapData(320,455,true,0);
bitmapData.draw(tempCan,_matrix);
var codeStr:String = ImageSnapshot.encodeImageAsBase64( ImageSnapshot.captureImage( bitmapData ) );
tempCan.rawChildren.removeChild(bt);
bitmapData.dispose();
bitmapData = null
return codeStr;
}
提供本文中所有as3的源代码下载,后台可以用自己熟悉的任何一门语言写写就好:java、.net、python或是其它…