How to drag and drop a file from outside to your flex or AIR application and render it correctly?

By | April 7, 2012

Actually we have to do this by registering your application with the eventlisteners for NATIVE_DRAG_ENTER and NATIVE_DRAG_DROP.
The following code shows how to do this.
Just copy and paste the code to your MXML file and see the result.
Drag and drop an image file from outside to your AIR application.


        import mx.controls.Alert;
        import mx.controls.Image;
        import flash.filesystem.File;

        private function init():void{
               this.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER,onDragIn);
               this.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP,onDrop);
        }

        private function onDragIn(event:NativeDragEvent):void{
          NativeDragManager.acceptDragDrop(this);
        }

        private function onDrop(event:NativeDragEvent):void{
          var dropfiles:Array = event.clipboard.getData(ClipboardFormats.FILE_LIST_FORMAT) as Array;
          for each (var file:File in dropfiles){
            switch (file.extension.toLowerCase()){
              case "png" :
                addImage(file.nativePath);
                    break;
              case "jpg" :
                addImage(file.nativePath);
                break;
              case "jpeg" :
                addImage(file.nativePath);
                break;
              case "gif" :
                addImage(file.nativePath);
                break;
              default:
                Alert.show("Unmapped Extension");
              }
            }
          }

          private function addImage(nativePath:String):void{
            var i:Image = new Image();
            if(Capabilities.os.search("Mac") >= 0){
              i.source = "file://" + nativePath;
            } else {
              i.source = nativePath;
            }
            this.addChild(i);
          }
        ]]>

Leave a Reply

Your email address will not be published. Required fields are marked *