Batch-after-Batch Multiple File Uploader in Flash 8 (Source Code)

Posted: January 26, 2011 in Flash ActionScript, PHP
Tags: , , , , , , , ,

This is the source code of the “batch-after-batch” multiple file uploader in Flash 8 (ActionScript 2.0) demonstrated at http://demo.programmerspride.com/flash-batch-after-batch-multi-uploadlive demo.

flash multiple file uploader

import flash.net.FileReference;
import flash.net.FileReferenceList;
import flash.external.ExternalInterface;

var imageFiles:FileReferenceList = new FileReferenceList;
var list:Array = new Array(); // Handler to the selected files.
var listener:Object = new Object(); // The listener object that listens for FileReference events.
var upload_listener:Object = new Object();
imageFiles.addListener(listener);

// These next four (4) lines will just load the external "browse button".
// Parent movie clip.
mc.createEmptyMovieClip("img", getNextHighestDepth());

// Child movie clip that the image will replace.
mc.img.createEmptyMovieClip("image", 99);

// Create the image loader that loads the "browse button" as configured.
var loader:MovieClipLoader = new MovieClipLoader();
loader.loadClip(_root.btn_browse_name, mc.img.image);

// When the "browse button" is clicked.
mc.onPress = function():Void {
	
	// Actual browsing of Files
	imageFiles.browse([{
		description: _root.file_description,
		extension: _root.file_extension
	}]);
}

// When files are selected then call JS UI for enqueueing.
listener.onSelect = function():Void {
	
	list = imageFiles.fileList;
	var total:Number = list.length;
	
	if(total > 0) {
		
		ExternalInterface.call("img.clearqueue()");
		for(var i:Number = 0; i<total; i++) {
			
			// 0 = Size, 1 = True/False when accepted or not.
			var info:Array = getFileSize(list[i].size); 
			
			// Send filename to JS for queueing.
			ExternalInterface.call("img.enqueue('"+ list[i].name +"','"+ info[0] +"','"+
									info[1] +"')");
		}
	}
}

// Waits for some JS commands from the web-page document.
ExternalInterface.addCallback("upload", this, doFileUpload);
ExternalInterface.addCallback("cancel", this, doFileCancel);

function doFileUpload():Void {
	var total:Number = list.length;
	
	if(total > 0) {
		
		for(var i:Number = 0; i<total; i++) {
							
			// 0 = Size, 1 = True/False when accepted or not.
			var info:Array = getFileSize(list[i].size); 
			if(info[1] == true) { 
		
				list[i].addListener(upload_listener);
				list[i].upload("upload.php?sessid="+ _root.session_id);
			}
		}
		
	} else ExternalInterface.call("img.empty()");
}

// This function is triggered when an item is cancelled by User.
function doFileCancel(filename:String):Void {
	
	doRemoval(filename);
	ExternalInterface.call("img.cancelled('"+ filename +"','"+ ((list.length == 0) ? 1 : 0) +"')");
}

function doRemoval(filename:String) {
	
	var index:Number = getFileIndex(filename);
	
	list[index].cancel(); // Actual cancelling from the memory queue.
	list[index].removeListener(upload_listener); // Remove attached process handlers.
	
	list.splice(index, 1); // Dont' use .pop() in removing an item. Use .splice() instead.
}

upload_listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void {
	
	var p:Number = Math.round((bytesLoaded / bytesTotal) * 100);
	var tmp:Array = getFileSize(bytesLoaded);
	
	ExternalInterface.call("img.progress('"+ p +"','"+ file.name +"','"+ tmp[0] +"')");
};

upload_listener.onComplete = function(file:FileReference):Void {
	
	var filename:String = file.name;
	doRemoval(filename);
	ExternalInterface.call("img.uploaded('"+ filename +"','"+ ((list.length == 0) ? 1 : 0) +"')");
};

upload_listener.onHTTPError = function(file:FileReference, httpError:Number):Void {

	ExternalInterface.call("this.onError('"+ file.name +"','HTTP Error: "+ httpError +"')");
}

upload_listener.onIOError = function(file:FileReference):Void {

	ExternalInterface.call("this.onError('"+ file.name +"','I/O Error')");
}

upload_listener.onSecurityError = function(file:FileReference, errorString:String):Void {

	ExternalInterface.call("this.onError('"+ file.name +"','Security Error: "+ errorString +"')");
}

Initializing the custom “browse” button:

Stage.scaleMode = "noscale";

var canvas_width:Number = 250;
var canvas_height:Number = 50;

if(_root.btn_browse_width > canvas_width) canvas_width = _root.btn_browse_width;
if(_root.btn_browse_height > canvas_height) canvas_height = _root.btn_browse_height;

var xPosition:Number = ((canvas_width - _root.btn_browse_width) / 2);
var yPosition:Number = ((canvas_height - _root.btn_browse_height) / 2);

mc._x = xPosition;
mc._y = yPosition;

Miscellaneous:

function getFileIndex(filename:String):Number {
	
	var total:Number = list.length;
	if(total > 0) { 
		for(var i:Number = 0; i<total; i++) { 
			if(list[i].name == filename) { 
			
				return i;
			}
		}
	}
	
	return -1;
}

function getFileSize(filesize:Number):Array {
	
	var bytes:Number = filesize;
	var unit:String = "B";
	var accept:Boolean = true;
	
	if(bytes < 1073741824) { // If less than GB
		
		// Means MB ( 1024 * 1024 )
		if(bytes >= 1048576) { // If greater or equal to MB but less than GB
			
			bytes = (bytes / 1024 / 1024);
			unit = "MB";		
		}
		else {
			
			// Means KB ( 1024 )
			if(bytes >= 1024) { // If greater or equal to KB but less than MB
				
				bytes = (bytes / 1024);
				unit = "KB";		
			}			
		}
	}
	else {
		
		// Too large.
		accept = false;
	}
	
	if(unit != "B") {

		// Round it off in 2 decimal places
		bytes = (Math.round(bytes * Math.pow(10, 2)) / Math.pow(10, 2))
	}
	
	if(bytes > _root.file_size_max && unit == "MB") accept = false;
	
	return [bytes +" "+ unit, accept];
	
}
Advertisements
Comments
  1. Great tutorial.

    Is it possible to point the uploads to any given directory?

    Thank you.

  2. SPS says:

    Hi Malcolm, thanks for dropping by, yes you can specify any directory where to upload, all of that can be done inside the server-side script (upload.php specified at line 069).

    Cheers …

  3. Thank you for your reply.

    I am a bit of a novice at actionscript but when I look at line 069
    list[i].upload(“upload.php?sessid=”+ _root.session_id);

    Would I be correct in saying this is actionscript looking for a variable “session_id” passed by PHP?

    If I use

    in upload.php

    Or if I pass the value using “flashvars” it seems to work fine and it appears as though the files have been uploaded but for some reason when I look for them I can not see them anywhere.

    And if I alter any of the actionscript code on line 069 between () or after “upload.php?sessid=” the file progress bar reaches 100% but then just sit’s there.

    I am probably missing something simple but I just dont seem to be able to get it to work.

    Thank You.

  4. Sorry some text was missing.

    If I use

    in upload.php

    Or if I pass the value using “flashvars” it seems to work fine and it appears as though the files have been uploaded but for some reason when I look for them I can not see them anywhere.

    And if I alter any of the actionscript code on line 069 between () or after “upload.php?sessid=” the file progress bar reaches 100% but then just sit’s there.

    I am probably missing something simple but I just dont seem to be able to get it to work.

    Thank You.

  5. oops! sorry I had to remove the php tags.

    If I use PHP

    $session_id= “uploads”;
    print(“&session_id=$session_id”);

    in upload.php

    Or if I pass the value using “flashvars” it seems to work fine and it appears as though the files have been uploaded but for some reason when I look for them I can not see them anywhere.

    And if I alter any of the actionscript code on line 069 between () or after “upload.php?sessid=” the file progress bar reaches 100% but then just sit’s there.

    I am probably missing something simple but I just dont seem to be able to get it to work.

    Thank You.

  6. SPS says:

    Hi Malcolm, thanks for visiting again.

    Ok, I don’t blame you if you cannot make it work for the first time since this code was just grabbed from a finished product.

    In your upload.php, you must have the code like this one below:

    move_uploaded_file($_FILES[‘Filedata’][‘tmp_name’], $_FILES[‘Filedata’][‘name’]);

    This piece of code is the one to actually uploads the file(s).

    If you want to put the file(s) inside a directory, let’s say “images” then just create a folder named “images” relative to upload.php and change the code to:

    move_uploaded_file($_FILES[‘Filedata’][‘tmp_name’], ‘images/’ . $_FILES[‘Filedata’][‘name’]);

    Just let me know of any help I can offer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s