2011년 3월 10일 목요일

서버에 File Upload 하기 [출처] 서버에 File Upload 하기|작성자 위니

package {
       import flash.display.Sprite;
       import flash.events.Event;
       import flash.events.MouseEvent;
       import flash.net.FileFilter;
       import flash.net.FileReference;
       import flash.net.URLRequest;
       import flash.net.URLRequestMethod;
       import flash.net.URLVariables;

       public class FileUpload extends Sprite {

             /**
                *셋팅 되어 있는 서버 경로...
                * !! 주의 !! 서버 폴더의 퍼미션 설정을 반드시  !. write  체크 되어 있어야 합니다.
                방법 : ftp -> remote site -> 원하는 폴더 선택 우클릭 -> 퍼미션 설정 모드. 
                */
             public static const SERVER_PATH:String="";

             /**
                파일 레퍼런스 변수.
                * myType -> brows 에서는 타입을 배열로 받기 때문에 img, text  따로 생성하여 myType담아야 한다.
                */
             private var fileRef:FileReference;

             private var myType:Array=[];


             /**
                초기화 부분.
                */

             public function FileUpload() {
                    super();


                    // 초기화
                    this.defaultSetting();
                    this.initLayout();
                    this.initEvents();

                    // 업로드 시작을 기다리는 리스너
                    stage.addEventListener(MouseEvent.CLICK,onClick);
             }


             private function defaultSetting():void {

                    if (SERVER_PATH=="") {

                           trace("SERVER_PATH  설정해주세요");

                    }
                    this.fileRef=new FileReference  ;

                    // 업로드 타입
                    var imgType:FileFilter=new FileFilter("Images (*.jpg, *.jpeg, *.gif)","*.jpg; *.jpeg; *.gif");
                    var txtType:FileFilter=new FileFilter("Texts (*.txt, *.hwp)","*.txt; *.hwp");

                    this.myType.push(imgType);
                    this.myType.push(txtType);
             }

             private function initLayout():void {

             }

             private function initEvents():void {
                    this.fileRef.addEventListener(Event.SELECT,onSelect);
                    this.fileRef.addEventListener(Event.COMPLETE,onComplete);
             }

             /**
                *
                * @ 파일을 선택 했을 경우 처리 메소드.
                *   변수를 추가하여 전송할 수도 있고컨텐츠 타입전송방법( GET, POST ) 등을 설정한다.
                *   다수의 파일을 한번에 처리하고자  경우 FileReference -> FileReferenceList  한다.
                *
                *   파일이 없는 경우 FileReference 말고 URLLoader  처리하도록 변경해야 .
                *
                */
             private function onSelect(e:Event):void {

                    // 변수 추가하는 방법 ----------------------------------------------
                    var param:URLVariables=new URLVariables  ;
                    param.date=new Date  ;
                    param.id="1234-5678-90";

                    // URLRequest 설정 -----------------------------------------------
                    var url:String=FileUpload.SERVER_PATH+"/test/fileRef.php";
                    var req:URLRequest=new URLRequest(url);
                    req.method=URLRequestMethod.POST;
                    req.contentType="multipart/form-data";
                    req.data=param;

                    try {
                           this.fileRef.upload(req);
                    catch (e:Error) {
                           trace("Unable to Upload this file");
                    }
             }

             // 업로드 완료 --------------------------------
             private function onComplete(e:Event):void {
                    var name:String=e.target as FileReference.name;
                    trace(name+" Upload Complete");
             }

             // 스테이지를 클릭 했을 경우 셀렉트 브라우저 오픈 ---------------
             private function onClick(e:MouseEvent):void {
                    try {
                           fileRef.browse(this.myType);
                    catch (e:Error) {
                           trace(e.getStackTrace());
                    }
             }
       }
}

# as3 기초. curveTo 를 이용한 베지어 곡선 그리기. [출처] # as3 기초. curveTo 를 이용한 베지어 곡선 그리기.|작성자 위니

곡선을 as로 표현할 때 어떻게 적용되는지 궁금해서 테스트를 해봤습니다.
재미를 위해 enterframe 으로 돌려봤습니다.

moveTo() 는 시작점을 나타내는 것이므로..
드로잉 툴을 이용한다고 가정 했을 때, 가상의 x,y좌표로 마우스를 가져간다고 보시면 됩니다.

lineTo()는 일직선을 그리므로 목표지점 x,y 좌표를 찍어주면 되지만~
이와달리 curveTo()는 인자를 4개 받는군요.

curveTo(controlX:Number, controlY:Number, anchorX:Number, anchorY:Number)
여기서 controlX, controlY 는 거쳐갈 점을 의미합니다.
즉, 어느 쪽으로 얼마나 휘게 될지는 controlX, controlY에 의해 좌우된다고 보시면 되겠습니다.

anchorX,Y는 lineTo의 목표지점과 같은 의미이고요.

아래 예제에서 보시면 아시겠지만~
목표지점을 라인이 통과하지 않습니다. 베지어 곡선의 형태로

위와같이 작동합니다.


그림대로라면
moveTo()의 x,y는 P0
controlX, Y 는 P1 이 되겠고요..
anchorX, Y 는 P2 가 되겠네요.


아래는 실행 예제 입니다.




======================================== source =========================================

package
{
       import flash.display.Shape;
       import flash.display.Sprite;
       import flash.events.Event;

       [SWF(width='1024', height='700', backgroundColor='#ffffff', frameRate='30')]
       public class DrawCurve extends Sprite
       {
            
             private var roundObject : Shape;
            
             public function DrawCurve()
             {
                    super();
                   
                    this.roundObject           new Shape();
                    this.addChild( roundObject );
                    this.addEventListener( Event.ENTER_FRAME, onEnter );
             }
            
             private function onEnter( e:Event ):void
             {
                    this.roundObject.graphics.clear();
                    roundObject.graphics.lineStyle( 1, 0x000000 );
                    roundObject.graphics.moveTo( 100 , 100);
                    roundObject.graphics.curveTo(this.mouseX, this.mouseY, 400, 400);
             }
            
       }
}

ExternalInterface.call("eval", 변수명 ) [출처] ExternalInterface.call("eval", 변수명 )|작성자 위니

자바스크립트의 변수를 플래시가 직접 가져올 수 있는!!

엄청난 방법이 있습니다. 

안지는 약 1년 되었는데 -_-; 이제 활용해보니 실로 엄청 나네요.... 

까먹고 계속 콜백 함수 이용했던 제가 부끄럽습니다 ㅠ_ㅠ;



자바스크립트 내장 함수까지 호출 한다니.. 멋지죠.. 

ExternalInterface.call("eval","document.URL" )

이렇게 하면 현재 자신의 wrapper url 이 나옵니다.


// js
var myVar = new Array();
// as3
ExternalInterface.call("eval","myVar" )

이렇게하면 배열이나 오브젝트도 참조되구욤.... 멋지죠!


많이 사용하세욤..

웹컴으로 캡쳐한 이미지 로컬에 저장하기

http://aner2000.blog.me/90065445643

pg 인코더. 사용해서.. bitmap -> byteArray로 서버에 전송하기 ( 첨부파일 : 서버에 저장하는 샘플 ) [출처] jpg 인코더. 사용해서.. bitmap -> byteArray로 서버에 전송하기 ( 첨부파일 : 서버에 저장하는 샘플 )|작성자 위니

First Things First
Before we get started, make sure to grab the ActionScript 3 Core Library. The Core Library contains several classes and utilities that make it easy to do things such as MD5 hashing, date formatting, and image encoding to name a few. Once you have the library, just drop it into your classes folder and you are ready to go. Now we can import the JPGEncoder.

import com.adobe.images.JPGEncoder;

Encoding the MovieClip
In this example, we are going to assume that our MovieClip of interest is named sketch_mc. In order to make use of the JPEGEncoder, our MovieClip needs to become a bitmap. To do this, we are going to use the BitmapData class. The contructor for this class requires two arguments: width and height. Since we want our jpeg to be the same size as sketch_mc, we use it’s width and height properties. Then by using sketch_mc as an argument, the draw method draws our MovieClip on to the bitmap.

import com.adobe.images.JPGEncoder;

var jpgSource:BitmapData = new BitmapData (sketch_mc.width, sketch_mc.height);
jpgSource.draw(sketch_mc);

Now that sketch_mc is in bitmap form, we can use the JPGEncoder. When creating a new instance of this class, you can set the level of compression by passing in a number from 1 - 100. Then to create our jpeg, we call the encode method and use our BitmapData instance as the argument. The encode method returns the jpeg in the form of a ByteArray, which is simply an AS3 class that makes working with binary data a little easier.

import com.adobe.images.JPGEncoder;

var jpgSource:BitmapData = new BitmapData (sketch_mc.width, sketch_mc.height);
jpgSource.draw(sketch_mc);

var jpgEncoder:JPGEncoder = new JPGEncoder(85);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);

From the Flash Player to the Hard Drive
ActionScript 3 has done all the work neccessary to turn our MovieClip into a jpeg, but it needs a little help in making it available to download. To make this happen, we will need to post our ByteArray to a server side script using the URLRequest class. Since we are posting binary data, we must set the content-type to “application/octet-stream”. It is also important to note that the file being downloaded will need a name, so we pass that to our server side script as a query string.

import com.adobe.images.JPGEncoder;

var jpgSource:BitmapData = new BitmapData (sketch_mc.width, sketch_mc.height);
jpgSource.draw(sketch_mc);

var jpgEncoder:JPGEncoder = new JPGEncoder(85);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);

var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
var jpgURLRequest:URLRequest = new URLRequest("jpg_encoder_download.php?name=sketch.jpg");
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = jpgStream;
navigateToURL(jpgURLRequest, "_blank");



php 소스 엮인글 - 
http://blog.naver.com/kjhbond/50082537619 - 서버에 저장하는 php 구문
http://blog.naver.com/kjhbond/50082538671 - 로컬 컴퓨터에 저장하는 php 구문 ( 테스트 브라우저 : 크롬 )

Google Tweener

http://cafe.naver.com/bfsg.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=2106&