<pedrocorreia.net ⁄>
corner
<mySearch ⁄> <mySearch ⁄>

corner
 
corner
<mySnippets order="rand" ⁄> <mySnippets order="rand" ⁄>

corner
 
corner
<myContacts ⁄> <myContacts ⁄>

<email ⁄>


pc@pedrocorreia.net

<windows live messenger ⁄>


pedrojacorreia@hotmail.com

<myCurriculum type="pdf" ⁄>


Download
corner
 
corner
<myBlog show="last" ⁄> <myBlog show="last" ⁄>

corner
 
corner
<myNews show="rand" ⁄> <myNews show="rand" ⁄>

corner
 
corner
<myNews type="cat" ⁄> <myNews type="cat" ⁄>

corner
 
corner
<myQuote order="random" ⁄> <myQuote order="random" ⁄>

corner
 
corner
<myPhoto order="random" ⁄> <myPhoto order="random" ⁄>

<pedrocorreia.net ⁄>
corner
 
corner
<myAdSense ⁄> <myAdSense ⁄>

corner
 
corner
<myVisitorsMap ⁄> <myVisitorsMap ⁄>

corner
 
 

<Actionscript File Upload ⁄ >




clicks: 9348 9348 2010-07-23 2010-07-23 goto mySnippets mySnippets actionscript  Download  Bookmark This Bookmark This



File uploading's a common thing nowadays, from a forum, to a blog, or even you're personal website, it's really a very common task.


Usually we use html <form> to make such operation, we can even use Ajax, but in this snippet I'll give an example to file uploading, but with Flash, Actionscript 2.

Let's just build a simple class that gives you a few detailed informations about the file being uploaded.

In this snippet I'll only make a single file upload at once support, in the future I'll build a multiple-file upload.



Building a Class will allow us to re-use our code more often and in other projects, the class itself will do all the work, we'll only have to pass the correct values, so that everything will work fine.





If you already made/ worked in, a file upload using ajax you'll notice that in Actionscript things will work, more or less in the same, way. The communication/ transfer will be asynchronous. For this communication we'll use an Actionscript class named FileReference

Since Flash's a client-side language, we'll still need some server-side scripting, such as PHP (as equal in Ajax file-upload).



I "designed" a rather simple interface:


  • a Browse Button

  • an Upload Button

  • a textbox on which we'll display our filename and a few upload information

  • a textbox on which we'll show a numeric progress indicator (0 – 100%)





The class will allow us to create a progressing bar indicator too, but it'll build it automatically, as you'll see, later, in the code. Such tasks are optional, this is, you only use it as you care, besides this snippet being a simple upload class on which I tried to not overload the class, you can make some customizations.


Here's a screenshot of our interface:






As you'll also see we have a line of code in the previous screenshot, it'll include "Init.as", which will take care of the all process for us, if you don't write Actionscript



Here's a tip, try to code always in separate Actionscript file, it'll save you some time when you need to update



Here's a screenshot before start uploading:












FileUpload.as, this is our main Class, it'll communicate with the server and show the user information about file being uploaded. You can use it in another completely different project or layout, as long as you specify the valid arguments, you can also freely customize it to your own needs.

  1. import flash.net.FileReference;
  2.  
  3. /**
  4. * This class will allow us to upload files
  5. *
  6. * @author pedrocorreia.net
  7. * @see http://flash-reference.icod.de/flash/net/FileReference.html
  8. */
  9. class FileUpload {
  10.  
  11. private var _file_reference: FileReference;
  12.  
  13. private var _script_upload:String = "";
  14. private var _script_upload_params:Object = { };
  15.  
  16. private var _file_type_extensions:String = "*.*";
  17. private var _file_type_description:String = "All Files";
  18.  
  19. private var _btn_browse:Button;
  20. private var _btn_upload:Button;
  21. private var _txt_console:TextField;
  22. private var _txt_progress:TextField;
  23. private var _progress_bar:Object = { };
  24.  
  25. private static var _progress_bar_mc:String = "ProgressBar_mc";
  26.  
  27. private var _messages = { };
  28.  
  29. /**
  30. * Constructor
  31. *
  32. * @param Object Settings
  33. */
  34. public function FileUpload (settings:Object) {
  35. this._script_upload = settings._script_upload;
  36. this._script_upload_params = settings._script_upload_params;
  37.  
  38. this._file_type_extensions = settings._file_type_extensions;
  39. this._file_type_description = settings._file_type_description;
  40.  
  41. this._btn_upload = settings._btn_upload;
  42. this._btn_browse = settings._btn_browse;
  43. this._txt_console = settings._txt_console ;
  44. this._txt_progress = settings._txt_progress;
  45. this._progress_bar = settings._progress_bar;
  46.  
  47. this._messages = settings._messages;
  48. }
  49.  
  50. /**
  51. * Initialize
  52. */
  53. public function Init():Void {
  54. var
  55. $this = this,
  56. _file_listener = {
  57. onSelect: function() { $this.__Selected(); } ,
  58. onOpen: function() { $this._Start(); },
  59. onProgress: function(file:FileReference, bytesLoaded:Number, bytesTotal:Number) {
  60. var
  61. _transferred:Number = Math.floor(bytesLoaded / 1024) ,
  62. _total:Number = Math.floor(bytesTotal / 1024) ,
  63. _remaining:Number = _total - _transferred,
  64. _verbose_output:String = " (" + _transferred + "MB / " + _remaining + "MB / " + _total + "MB)";
  65.  
  66. $this.__SetProgressText(Math.ceil((bytesLoaded / bytesTotal) * 100) + "%");
  67. $this.__SetConsoleText($this._messages._file_transferring + ": " + $this._file_reference.name + _verbose_output);
  68.  
  69. if ($this._progress_bar) { //check if progress bar indicator's enabled
  70. var
  71. _bar = $this._progress_bar._where["inner" + FileUpload._progress_bar_mc],
  72. _cur_width = $this._progress_bar._width;
  73.  
  74. _bar._width = (bytesLoaded * _cur_width) / bytesTotal;
  75. }
  76. },
  77. onComplete: function() { $this._Complete(); },
  78. onHTTPError: function() { $this._Error(); },
  79. onIOError: function() { $this._Error(); },
  80. onSecurityError: function() { $this._Error(); }
  81. };
  82.  
  83. this._file_reference = new FileReference();
  84. this._file_reference.addListener(_file_listener);
  85.  
  86. this._btn_upload._visible = false;
  87. this.__DrawProgressBar();
  88.  
  89. this.__CreateEvent(this._btn_browse, "Release", function() { $this._Browse(); });
  90. this.__CreateEvent(this._btn_upload, "Release", function() { $this._Upload(); });
  91. }
  92.  
  93. /**
  94. * Browse dialog
  95. */
  96. private function _Browse():Void {
  97. this._file_reference.browse([ {
  98. description: this._file_type_description,
  99. extension: this._file_type_extensions
  100. }]
  101. );
  102. }
  103.  
  104. /**
  105. * Will occur when the file's opened to start transferring
  106. */
  107. private function _Start():Void {
  108. this._btn_upload._visible = false;
  109. this.__SetConsoleText(this._messages._file_transferring + ": " + this._file_reference.name);
  110. this.__SetProgressText("0%");
  111. this.__ResetProgressBar();
  112. }
  113.  
  114. /**
  115. * Upload file
  116. */
  117. private function _Upload():Void {
  118. if (!this._script_upload) {return; }
  119.  
  120. //query string parameters
  121. var _query = [];
  122. for (var param in this._script_upload_params) {
  123. _query.push(param + "=" + this._script_upload_params[param]);
  124. }
  125. this._btn_browse._visible = false;
  126. this._file_reference.upload(this._script_upload + ((_query.length === 0) ? "" : "?" + _query.join("&")));
  127. }
  128.  
  129. /**
  130. * Will occur on transfer file error
  131. */
  132. private function _Error():Void {
  133. this.__SetConsoleText(this._messages._file_upload_error + ": " + this._file_reference.name)
  134. this.__HideProgressBar();
  135. this._btn_browse._visible = true;
  136. this._btn_upload._visible = !(this._btn_browse._visible);
  137. }
  138.  
  139. /**
  140. * Will occur on transfer complete sucessfully
  141. */
  142. private function _Complete():Void {
  143. this.__SetConsoleText(this._messages._file_upload_success + ": " + this._file_reference.name + " (" + Math.floor(this._file_reference.size / 1024) + "MB)");
  144. this._btn_upload._visible = false;
  145. this._btn_browse._visible = !this._btn_upload._visible;
  146. }
  147.  
  148. /**
  149. * Show Upload button
  150. */
  151. private function __Selected():Void {
  152. if(this._txt_console){
  153. this._txt_console.text = this._messages._file_selected + ": " + this._file_reference.name + " (" + Math.floor(this._file_reference.size / 1024) + "MB)";
  154. }
  155. this._btn_upload._visible = true;
  156. }
  157.  
  158. /**
  159. * Draw ProgressBar indicator
  160. */
  161. private function __DrawProgressBar():Void {
  162. if (!this._progress_bar) return;
  163.  
  164. var
  165. _bar = this._progress_bar,
  166. /**
  167. * Draw Rounded MovieClip
  168. *
  169. * @param String MovieClip ID
  170. * @param MovieClip Create where
  171. * @param Number Width
  172. * @param Number Height
  173. * @param Number X Position
  174. * @param Number Y Position
  175. * @param Number Background Color
  176. * @param Number Border Color
  177. * @param Number Border Width
  178. * @param Boolean Visibility
  179. *
  180. */
  181. drawRoundedRect = function(id:String, where:MovieClip, w:Number, h:Number, x:Number, y:Number, bg_color:Number, brd_color:Number,brd_width:Number, visibility:Boolean):Void {
  182. var bar:MovieClip = where.createEmptyMovieClip(id, where.getNextHighestDepth());
  183. bar.lineStyle(brd_width, brd_color, 100, true, "none", "round", "miter", 1);
  184. bar.beginFill(bg_color);
  185. bar.lineTo(w, 0);
  186. bar.lineTo(w, h);
  187. bar.lineTo(0, h);
  188. bar.lineTo(0, 0);
  189. bar.endFill();
  190. bar._width = w;
  191. bar._x = x;
  192. bar._y = y;
  193. bar._visible = visibility;
  194. };
  195.  
  196. drawRoundedRect(
  197. FileUpload._progress_bar_mc,
  198. _bar._where,
  199. _bar._width, _bar._height, _bar._x, _bar._y,
  200. _bar._canvas_color, _bar._border_color, _bar._border_width,
  201. true
  202. );
  203.  
  204. drawRoundedRect(
  205. "inner" + FileUpload._progress_bar_mc,
  206. _bar._where,
  207. _bar._width, _bar._height, _bar._x, _bar._y,
  208. _bar._bg_color, _bar._border_color, _bar._border_width,
  209. false
  210. );
  211. }
  212.  
  213. /**
  214. * Set Console text
  215. *
  216. * @param String
  217. */
  218. private function __SetConsoleText(text:String):Void {
  219. if (!this._txt_console) return;
  220. this._txt_console.text = text;
  221. }
  222.  
  223. /**
  224. * Set ProgressText value
  225. *
  226. * @param String
  227. */
  228. private function __SetProgressText(text:String):Void {
  229. if (!this._txt_progress) return;
  230. this._txt_progress.text = text;
  231. }
  232.  
  233. /**
  234. * Reset ProgressBar
  235. * @param Boolean Visibility
  236. */
  237. private function __ResetProgressBar(visibility:Boolean):Void {
  238. if (!this._progress_bar) return;
  239.  
  240. if (!visibility) { visibility = true; }
  241. this._progress_bar._where["inner" + FileUpload._progress_bar_mc]._w = 0;
  242. this._progress_bar._where["inner" + FileUpload._progress_bar_mc]._visible = visibility;
  243. }
  244.  
  245. /**
  246. * Hide ProgressBar
  247. */
  248. private function __HideProgressBar():Void { this.__ResetProgressBar(false); }
  249.  
  250. /**
  251. * Auxiliary function to add an EventHandler
  252. *
  253. * @param Button Element
  254. * @param String Event Name
  255. * @param Function Callback Function
  256. */
  257. private function __CreateEvent(elem:Button, evt:String, callback:Function):Void{
  258. elem["on" + evt] = callback;
  259. }
  260.  
  261. } //end class FileUpload








Init.as, this is where we'll specify our settings to FileUpload class. The code's throughout self explanatory. In here you'll specify the settings such as the the upload script; your buttons; user messages; file extensions allowed and its description; progress bar settings, etc, etc.
Since there are many arguments, we'll use an Object to declare all our settings.

As I said before, we'll still have to use a server-side script also, because Flash's only a client-side scripting language. Besides uploading the file to the server, you can also send some information, just like a query string, or some fields in our regular html <form> tag. In our settings Object we have a parameter called "_script_upload_params", here's where you'll specify all the information that you want to send along with the file.

  1. //used when loading as external swf, it's not strictly necessary,
  2. //however it could save you a few headaches with paths ^_^''
  3. _root._lockroot = true;
  4.  
  5. var
  6. //cache our current "this"
  7. $self = this,
  8.  
  9. //save path to form, in this example it's the same, however it could be different,
  10. //for instance, our form was inside a MovieClip, in this case it would be
  11. //$path = $self.myMovieClipName;
  12. $path = $self,
  13.  
  14. settings = {
  15. //server script that will upload the file(s)
  16. _script_upload: "upload.php",
  17.  
  18. //query string parameters (optional)
  19. //use this if you want to send information to the server
  20. _script_upload_params: {
  21. dummy_x: "lorem",
  22. dummy_y: "ipsum",
  23. id: "123456"
  24. },
  25.  
  26. //user messages (optional)
  27. _messages: {
  28. _file_upload_success: "File uploaded succefully",
  29. _file_upload_error: "Error while transferring file",
  30. _file_selected: "File selected",
  31. _file_transferring: "File being transferred"
  32. },
  33.  
  34. //allowed extensions
  35. _file_type_extensions: "*.mp3; *.wav",
  36.  
  37. //allowed extensions description
  38. _file_type_description: "Files MP3 Files (*.mp3; *.wav)",
  39.  
  40. //upload button
  41. _btn_upload: $path["btn_upload"],
  42.  
  43. //browse button
  44. _btn_browse: $path["btn_browse"],
  45.  
  46. //textbox that will show the informations to the user (optional)
  47. _txt_console: $path["txt_console"],
  48.  
  49. //textbox that will show the % progress (optional)
  50. _txt_progress: $path["txt_progress"],
  51.  
  52. //progress bar (optional), customize it at your own needs
  53. _progress_bar: {
  54. _width: $path["txt_progress"]._width,
  55. _height: $path["txt_progress"]._height,
  56. _x: $path["txt_progress"]._x + 4,
  57. _y: $path["txt_progress"]._y + 30,
  58. _bg_color: 0xD15600,
  59. _canvas_color: 0xFFFFBD,
  60. _border_color: 0x3F4C6B,
  61. _border_width: 5,
  62. _where: $path
  63. }
  64. },
  65.  
  66. //create FileUpload object
  67. file_uploader = new FileUpload(settings);
  68.  
  69. //initialize our FileUploader and prepare all event handlers
  70. file_uploader.Init();




upload.php, this is our php file, you can use any server-side language.

  1. <?php
  2.  
  3. //these variables are the ones specified at "settings._script_upload_params", in Init.as
  4. //as already stated, these variables are optional, use them in case you want to
  5. //send some information to the server
  6. $dummy_x = $_POST["dummy_x"];
  7. $dummy_y = $_POST["dummy_y"];
  8. $id = $_POST["id"];
  9.  
  10. //move file
  11. move_uploaded_file($_FILES['Filedata']['tmp_name'], $_FILES['Filedata']['name']);
  12.  
  13. //your script goes here
  14. ?>




And finally, here goes a video of our script working ^_^''










If you have any doubt or found any error, please drop me an email.









clicks: 9348 9348 2010-07-23 2010-07-23 goto mySnippets mySnippets actionscript  Download  Bookmark This Bookmark This