Upload, download images and other files with AS3


/ Published in: ActionScript 3
Save to your folder(s)



Copy this code and paste it in your HTML
  1. package src
  2. {
  3.  
  4. /**
  5. * ImageCreator;
  6. *
  7. * @langversion ActionScript 3.0;
  8. * @playerversion Flash 9.0;
  9. *
  10. * @author [email protected];
  11. * @since 03.12.2008;
  12. *
  13. * @license http://creativecommons.org/licenses/by-nc-sa/3.0/
  14. */
  15.  
  16. import flash.display.*;
  17. import flash.events.*;
  18. import flash.text.*;
  19. import flash.geom.*;
  20. import flash.utils.*;
  21. import flash.net.*;
  22. import flash.system.*;
  23.  
  24. import src.events.*;
  25. import src.image.*;
  26. import src.file.*;
  27. import src.load.*;
  28. import src.ui.*;
  29.  
  30. import gs.TweenFilterLite;
  31.  
  32. public class ImageCreator extends Sprite
  33. {
  34.  
  35. //--------------------------------------
  36. // CUSTOM VARIABLES YOU'LL NEED TO ENTER
  37. //--------------------------------------
  38.  
  39. private var m_basePath : String = 'http://yourserver.com/project/'; // set this to your web server path 'http://YOURSITE.com/';
  40. private var m_uploadPath : String = 'uploads/'; // set this to the folder on your server where you will allow images to be uploaded ( folder permissions must be set to 777 );
  41. private var m_outputPath : String = 'output/'; // set this to the folder on your server where images should be created; ( folder permissions must be set to 777 );
  42.  
  43. //--------------------------------------
  44. // CONSTRUCTOR
  45. //--------------------------------------
  46.  
  47. public function ImageCreator ()
  48. {
  49. // allow script access;
  50. Security.allowDomain( '*' ); // replace * with your domain;
  51. Security.allowInsecureDomain( '*' ); // replace * with your domain;
  52.  
  53. // determine whether the swf is being accessed from the web or your local hard drive;
  54. m_isLocal = false;
  55.  
  56. // hide image creation options;
  57. creating.visible = false;
  58. creating.alpha = 0;
  59.  
  60. // set up file manager & basic interaction listeners on slight delay;
  61. TweenFilterLite.delayedCall( 0.5, init );
  62. }
  63.  
  64. //--------------------------------------
  65. // CLASS VARIABLES
  66. //--------------------------------------
  67.  
  68. // display items;
  69. public var upload : UIButton; // upload button on .fla stage;
  70. public var download : UIButton; // download button on .fla stage;
  71. public var create : UIButton; // create button on .fla stage;
  72. public var scribble : UIButton; // scrubble button on .fla stage;
  73. public var clear : UIButton; // clear button on .fla stage;
  74. public var creating : Sprite; // creating screen ( shows while image is being saved to sever );
  75.  
  76. // output container;
  77. private var m_output : Sprite = new Sprite(); // container for image;
  78. private var m_mask : Sprite = new Sprite(); // mask for image container;
  79. private var m_progress : Sprite = new Sprite(); // upload / download indicator;
  80. private var m_effect : Scribble; // covers image with random effect;
  81.  
  82. // vars;
  83. private var m_isLocal : Boolean; // determines if swf is on web server or local drive;
  84. private var m_fileMgr : FileManager; // manages the opening & upload of local files;
  85. private var m_imagePHP : String = 'image.php'; // file that will manage image upload on your server;
  86. private var m_finalImage : String; // final name of file on creation;
  87. private var m_imageQuality : Number = 90; // jpeg or png export quality;
  88. private var m_capture : Sprite; // set this equal to the sprite or movie clip that you wish to capture ( set to stage for entire movie );
  89. private var m_downloader : GraphicLoader; // handles image download ( after upload is complete );
  90. private var m_imageExtension : String = '.jpg'; // jpeg image extension;
  91.  
  92. //--------------------------------------
  93. // GETTER/SETTERS
  94. //--------------------------------------
  95.  
  96. /**
  97. * returns upload php file path based on whether or not the swf is a local publish or hosted on a web server;
  98. **/
  99. public function get uploadPath () : String
  100. {
  101. return m_basePath + m_imagePHP;
  102. }
  103.  
  104. /**
  105. * returns image creation php file path based on whether or not the swf is a local publish or hosted on a web server;
  106. **/
  107. public function get createPath () : String
  108. {
  109. return m_basePath + m_imagePHP;
  110. }
  111.  
  112. /**
  113. * returns image creation php file path based on whether or not the swf is a local publish or hosted on a web server;
  114. **/
  115. public function get downloadPath () : String
  116. {
  117. return m_basePath + m_uploadPath;
  118. }
  119.  
  120. /**
  121. * returns image creation php file path based on whether or not the swf is a local publish or hosted on a web server;
  122. **/
  123. public function get finalImagePath () : String
  124. {
  125. return m_basePath + m_outputPath + m_finalImage + m_imageExtension;
  126. }
  127.  
  128. /**
  129. * returns container for image capture container;
  130. **/
  131. public function get captureContainer () : Sprite
  132. {
  133. return m_capture;
  134. }
  135.  
  136. /**
  137. * sets container for image capture container;
  138. **/
  139. public function set captureContainer ( inContainer : Sprite ) : void
  140. {
  141. m_capture = inContainer;
  142. }
  143.  
  144. //--------------------------------------
  145. // EVENT HANDLERS
  146. //--------------------------------------
  147.  
  148. /**
  149. * browse for image files on click of upload button;
  150. **/
  151. private function onBrowse ( e : MouseEvent ) : void
  152. {
  153. m_fileMgr.browse();
  154. }
  155.  
  156. /**
  157. * run the image capture function on release of the create button;
  158. **/
  159. private function onCaptureImage ( e : MouseEvent ) : void
  160. {
  161. // make sure there is content to capture;
  162. if ( captureContainer.width <= 1 && captureContainer.height <= 1 ) throw new Error( 'ERROR : no content to capture;' );
  163.  
  164. // show image creation message;
  165. TweenFilterLite.to( creating, 1, { autoAlpha : 1 } );
  166.  
  167. // create image;
  168. captureImage();
  169. }
  170.  
  171. /**
  172. * track image upload progress;
  173. **/
  174. private function onUploadProgress ( e : CustomEvent ) : void
  175. {
  176. trace( 'image uploading : ' + e.params.percent );
  177.  
  178. m_progress.scaleX = e.params.percent;
  179. }
  180.  
  181. /**
  182. * fires when image upload is complete;
  183. **/
  184. private function onImageUploaded ( e : CustomEvent ) : void
  185. {
  186. var dPath : String = String( downloadPath + e.params.fileName );
  187.  
  188. trace( 'image ready for download at : ' + dPath );
  189.  
  190. m_downloader.loadURL( dPath );
  191. }
  192.  
  193. /**
  194. * track image download progress;
  195. **/
  196. private function onDownloadProgress ( e : CustomEvent ) : void
  197. {
  198. trace( 'image downloading : ' + e.params.percent );
  199.  
  200. m_progress.scaleX = 1 - e.params.percent;
  201. }
  202.  
  203. /**
  204. * fires on image download is complete;
  205. **/
  206. private function onImageDownloaded ( e : CustomEvent ) : void
  207. {
  208. trace( 'image downloaded' );
  209.  
  210. // get image from loader;
  211. var clip : DraggableImage = new DraggableImage( new Bitmap( e.params.loaded.bitmapData.clone() ) );
  212.  
  213. // add the image to the stage;
  214. captureContainer.addChildAt( clip, captureContainer.getChildIndex( m_effect ) );
  215.  
  216. // show create / clear options;
  217. showOptions();
  218. }
  219.  
  220. /**
  221. * fires after image is successfully created on your server;
  222. **/
  223. private function onImageCreated ( e : Event ) : void
  224. {
  225. trace( 'image created : ' + e );
  226.  
  227. // hide image creation message;
  228. TweenFilterLite.to( creating, 1, { autoAlpha : 0 } );
  229.  
  230. // show download button;
  231. TweenFilterLite.to( download, 0.5, { autoAlpha : 1 } );
  232.  
  233. // show download dialog for flash player versions < 10;
  234. onDownloadImage();
  235. }
  236.  
  237. /**
  238. * attempts to download image to local computer;
  239. **/
  240. private function onDownloadImage ( e : MouseEvent = null ) : void
  241. {
  242. m_fileMgr.download( finalImagePath, m_finalImage + m_imageExtension );
  243. }
  244.  
  245. /**
  246. * fires if there is an error creating the image;
  247. **/
  248. private function onImageCreationError ( e : * ) : void
  249. {
  250. trace( 'error : ' + e );
  251. }
  252.  
  253. /**
  254. * fires if there is an error during upload;
  255. **/
  256. private function onUploadError ( e : CustomEvent ) : void
  257. {
  258. trace( 'upload error' );
  259. }
  260.  
  261. /**
  262. * fires if there is an error during download;
  263. **/
  264. private function onDownloadError ( e : ErrorEvent ) : void
  265. {
  266. trace( 'download error' );
  267. }
  268.  
  269. /**
  270. * downloads image to swf;
  271. **/
  272. private function onGetCapturedImage ( e : MouseEvent ) : void
  273. {
  274. m_fileMgr.download( finalImagePath, m_finalImage + m_imageExtension );
  275. }
  276.  
  277. /**
  278. * creates random scribble all over stage;
  279. **/
  280. private function onScribble ( e : MouseEvent ) : void
  281. {
  282. m_effect.createEffect();
  283.  
  284. showOptions();
  285. }
  286.  
  287. /**
  288. * clears any image in the capture conatiner, and resets scribble graphics;
  289. **/
  290. private function onClearAll ( e : MouseEvent ) : void
  291. {
  292. // remove all child object ( except effect clip ) from capture area;
  293. while ( captureContainer.getChildAt( 0 ) is DraggableImage ) delete captureContainer.removeChildAt( 0 );
  294.  
  295. // reset the scribbles;
  296. m_effect.reset();
  297.  
  298. // hide create / clear options;
  299. hideOptions();
  300. }
  301.  
  302. //--------------------------------------
  303. // PRIVATE & PROTECTED INSTANCE METHODS
  304. //--------------------------------------
  305.  
  306. /**
  307. * set up file manager / button listeners;
  308. **/
  309. private function init () : void
  310. {
  311. // add output container to stage at 0,0;
  312. addChildAt( m_output, 0 );
  313.  
  314. // check to make sure stage is available ( which it wouldn't be if this class were instantiated from another class );
  315. if ( stage != null )
  316. {
  317. // set up stage;
  318. stage.align = StageAlign.TOP_LEFT;
  319. stage.scaleMode = StageScaleMode.NO_SCALE;
  320.  
  321. // create image mask that matches the stage height & width;
  322. with ( m_mask.graphics )
  323. {
  324. beginFill( 0x000000 );
  325. drawRect( 0, 0, stage.stageWidth, stage.stageHeight );
  326. }
  327.  
  328. var border : Sprite = new Sprite();
  329.  
  330. // draw border around stage;
  331. with ( border.graphics )
  332. {
  333. lineStyle( 0, 0x000000 );
  334. drawRect( 0, 0, stage.stageWidth - 1, stage.stageHeight - 1 );
  335. }
  336.  
  337. addChildAt( border, numChildren - 1 );
  338. }
  339.  
  340. // create progress indicator;
  341. with ( m_progress.graphics )
  342. {
  343. beginFill( 0x000000 );
  344. drawRect( 0, 0, upload.width, 1 );
  345. }
  346.  
  347. addChild( m_progress );
  348.  
  349. m_progress.x = upload.x;
  350. m_progress.y = upload.y + upload.height + 2;
  351.  
  352. // set container to use as image capture area;
  353. captureContainer = m_output;
  354.  
  355. // set capture container mask;
  356. captureContainer.mask = m_mask;
  357.  
  358. // add effect to image;
  359. m_effect = new Scribble();
  360.  
  361. captureContainer.addChild( m_effect );
  362.  
  363. // show upload / scribble buttons;
  364. upload.show();
  365. scribble.show();
  366.  
  367. // set progress bar to zero scale;
  368. m_progress.scaleX = 0;
  369.  
  370. // set up file manager;
  371. m_fileMgr = new FileManager( uploadPath, m_uploadPath );
  372. m_fileMgr.addEventListener( FileManager.ON_PROGRESS, onUploadProgress );
  373. m_fileMgr.addEventListener( FileManager.ON_UPLOAD_ERROR, onUploadError );
  374. m_fileMgr.addEventListener( FileManager.ON_IMAGE_UPLOADED, onImageUploaded );
  375.  
  376. // listen to buttons;
  377. upload.addEventListener( MouseEvent.CLICK, onBrowse );
  378. create.addEventListener( MouseEvent.CLICK, onCaptureImage );
  379. download.addEventListener( MouseEvent.CLICK, onDownloadImage );
  380. scribble.addEventListener( MouseEvent.CLICK, onScribble );
  381. clear.addEventListener( MouseEvent.CLICK, onClearAll );
  382.  
  383. // ensure that the top left corner of the draw area is included in the draw calculations by drawing an invisible 1px box at 0,0;
  384. var corner : Sprite = new Sprite();
  385.  
  386. // draw box;
  387. with ( corner.graphics )
  388. {
  389. beginFill( 0xFFFFFF, 0 );
  390. drawRect( 0, 0, 1, 1 );
  391. }
  392.  
  393. // add corner piece to container;
  394. captureContainer.addChild( corner );
  395.  
  396. // set up loader;
  397. m_downloader = new GraphicLoader();
  398. m_downloader.addEventListener( GraphicLoader.ON_LOAD_PROGRESS, onDownloadProgress );
  399. m_downloader.addEventListener( GraphicLoader.ON_LOAD_COMPLETE, onImageDownloaded );
  400. m_downloader.addEventListener( ErrorEvent.ERROR, onDownloadError );
  401.  
  402. hideOptions();
  403. }
  404.  
  405. /**
  406. * perform image capture and upload to server;
  407. **/
  408. private function captureImage () : void
  409. {
  410. // set up a new bitmapdata object that matches the dimensions of the captureContainer;
  411. var bmd : BitmapData = new BitmapData( m_mask.width, m_mask.height, true, 0xFFFFFFFF );
  412.  
  413. // draw the bitmapData from the captureContainer to the bitmapData object;
  414. bmd.draw( captureContainer, new Matrix(), null, null, null, true );
  415.  
  416. // create a new JPEG byte array with the adobe JPEGEncoder Class;
  417. var byteArray : ByteArray = new JPGEncoder( m_imageQuality ).encode( bmd );
  418.  
  419. // create and store the image name;
  420. m_finalImage = getUniqueName();
  421.  
  422. // set up the request & headers for the image upload;
  423. var urlRequest : URLRequest = new URLRequest();
  424. urlRequest.url = createPath + '?path=' + m_outputPath;
  425. urlRequest.contentType = 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary();
  426. urlRequest.method = URLRequestMethod.POST;
  427. urlRequest.data = UploadPostHelper.getPostData( m_finalImage + m_imageExtension, byteArray );
  428. urlRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );
  429.  
  430. // create the image loader & send the image to the server;
  431. var urlLoader : URLLoader = new URLLoader();
  432. urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
  433. urlLoader.addEventListener( Event.COMPLETE, onImageCreated );
  434. urlLoader.addEventListener( IOErrorEvent.IO_ERROR, onImageCreationError );
  435. urlLoader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onImageCreationError );
  436. urlLoader.load( urlRequest );
  437. }
  438.  
  439. /**
  440. * returns new string representing the month, day, hour, minute and millisecond of creation for use as the image name;
  441. */
  442. private function getUniqueName () : String
  443. {
  444. var d : Date = new Date();
  445.  
  446. return d.getMonth() + 1 + '' + d.getDate() + '' + d.getHours() + '' + d.getMinutes() + '' + d.getMilliseconds();
  447. }
  448.  
  449. /**
  450. * show create / clear options;
  451. **/
  452. private function showOptions () : void
  453. {
  454. create.show();
  455. clear.show();
  456. }
  457.  
  458. /**
  459. * hide create / clear options;
  460. **/
  461. private function hideOptions () : void
  462. {
  463. create.hide();
  464. clear.hide();
  465. download.hide();
  466. }
  467. }
  468. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.