Upload Library or captured images on iOS with Flex Mobile 4.6

梦想的初衷 提交于 2019-12-01 01:28:54

I think I found a solution for works for my case so I wanted to share it in case it can help someone out. shaunhusain's post definitely got me moving in the right direction. I was able to avoid using the Alchemy swc all together which saves a TON of time in the app. The key is this AS3 library I found that formats a URLRequest in a way that mimics a standard file upload POST operation. Here's the basic outline:

I have a small component called 'status' thats an overlay with an icon and status text for the user. When a user wants to add a photo, they get a ViewMenu with the choices to get the photo from their library or take a new photo. The meat of the code is below.

 //IMAGE HANDLING

//Helpful Links:
//http://www.quietless.com/kitchen/dynamically-create-an-image-in-flash-and-save-it-to-the-desktop-or-server/
//http://stackoverflow.com/questions/597947/how-can-i-send-a-bytearray-from-flash-and-some-form-data-to-php
// GET WRAPPER CLASS Here: http://code.google.com/p/asfeedback/source/browse/trunk/com/marston/utils/URLRequestWrapper.as


//This part is basically all based on http://www.adobe.com/devnet/air/articles/uploading-images-media-promise.html


  protected var cameraRoll:CameraRoll = new CameraRoll();

  //User choose to pick a photo from their library
  protected function chooseImage():void {
   if( CameraRoll.supportsBrowseForImage )
    {
      cameraRoll.addEventListener( MediaEvent.SELECT, imageSelected );
      cameraRoll.addEventListener( Event.CANCEL, browseCanceled );
      cameraRoll.addEventListener( ErrorEvent.ERROR, mediaError );
      cameraRoll.browseForImage();
    }  else {
              trace( "Image browsing is not supported on this device.");
    }
   }

    //User choose to take a new photo!
protected var cameraUI:CameraUI = new CameraUI();
protected function captureImage():void
{
     if( CameraUI.isSupported )
    {
      trace( "Initializing..." );
          cameraUI.addEventListener( MediaEvent.COMPLETE, imageSelected );
      cameraUI.addEventListener( Event.CANCEL, browseCanceled );
      cameraUI.addEventListener( ErrorEvent.ERROR, mediaError );
      cameraUI.launch( MediaType.IMAGE );
    } else {
      trace( "CameraUI is not supported.");
    }
}


private function browseCanceled (e:Event):void
{
    trace ("Camera Operation Cancelled");
}

private function mediaError (e:ErrorEvent):void
{
    trace ("mediaError");
}


private var dataSource:IDataInput;
private function imageSelected( event:MediaEvent ):void
    {
       trace( "Media selected..." );   

               var imagePromise:MediaPromise = event.data;
       dataSource = imagePromise.open();    
       if( imagePromise.isAsync )
       {
           trace( "Asynchronous media promise." );
           var eventSource:IEventDispatcher = dataSource as IEventDispatcher;            
           eventSource.addEventListener( Event.COMPLETE, onMediaLoaded );         
       } else {
           trace( "Synchronous media promise." );
        readMediaData();
       }
}

        private function onMediaLoaded( event:Event ):void
        {
            trace("Media load complete");
            readMediaData();
        }


        private function readMediaData():void
        {
            var imageBytes:ByteArray = new ByteArray();
            dataSource.readBytes( imageBytes );
            upload(imageBytes);
        }

        //OK Here's where it gets sent. Once the IDataInput has read the bytes of the image, we can send it via our custom URLRequestWrapper
                    //which will format the request so the server interprets it was a normal file upload. Your params will get encoded as well 
                    //I used Uploadify this time but I've used this Wrapper class in other projects with success 
        protected function upload( ba:ByteArray, fileName:String = null ):void
        {
            if( fileName == null ) //Make a name with correct file type
            {                
                var now:Date = new Date();
                fileName = "IMG" + now.fullYear + now.month +now.day +
                    now.hours + now.minutes + now.seconds + ".jpg";
            }

            var loader:URLLoader = new URLLoader();
            loader.dataFormat= URLLoaderDataFormat.BINARY;

            var params:Object = {};
            params.name = fileName;
            params.user_id = model.user.user_id;

            var wrapper:URLRequestWrapper = new URLRequestWrapper(ba, fileName, null, params);
            wrapper.url = "http://www.your-domain.com/uploadify.php";

            loader.addEventListener( Event.COMPLETE, onUploadComplete );
            loader.addEventListener(IOErrorEvent.IO_ERROR, onUploadError );
            loader.load(wrapper.request);           
        }

        private function onUploadComplete(e:Event):void
        {
            trace("UPLOAD COMPLETE");
            var bytes:ByteArray = e.currentTarget.data as ByteArray;
                            //Most likely you'd want a server response. It will be returned as a ByteArray, so you can get back to the string:
            trace("RESPONSE", bytes.toString());
        }

        private function onUploadError(e:IOErrorEvent):void
        {
            trace("IOERROR", e.text);
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!