Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

AJAX file upload

Ever wanted to upload files using AJAX like in GMAIL, without reloading the page? Now you can. Cross browser method to upload files using AJAX in only 1Kb of code.
How to use AJAX file upload you can find on this script homepage - free code and tutorials website.

/**
*
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
*
**/

AIM = {

	frame : function(c) {

		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);

		var i = document.getElementById(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}

		return n;
	},

	form : function(f, name) {
		f.setAttribute('target', name);
	},

	submit : function(f, c) {
		AIM.form(f, AIM.frame(c));
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},

	loaded : function(id) {
		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
			return;
		}

		if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML);
		}
	}

}

FILE UPLOADING WITH UNIQUE NAME

src_filename = params[:file][:name] 
if !src_filename.original_filename.empty? 
  hashed_name = Digest::SHA1.hexdigest(Time.now.to_s) 
  filename = "#{RAILS_ROOT}/public/attachments/" + hashed_name + "_" + src_filename.original_filename 
  if File.open(filename, 'w'){ |f| f.write(src_filename.read) }  
     attachment = Attachment.new 
     attachment.name = src_filename.original_filename 
     attachment.hashed_name = hashed_name 
     attachment.size = src_filename.size 
     comment.attachments << attachment 
  end  
end 


uploader.func.php

// Uploader.func.php, called by: uploader();

<?
function uploader($num_of_uploads=1, $file_types_array=array("mp3"), $max_file_size=10485760, $upload_dir="../mp3s/"){
  if(!is_numeric($max_file_size)){
   $max_file_size = 10485760;  // 10MB
  }
  if(!isset($_POST["submitted"])){
   $form = "<form action='".$PHP_SELF."' method='post' enctype='multipart/form-data'>";
   $form .= "<p><span class=artist>Artist:</span><br><input type='text' name='artist' value=\"".htmlentities(stripslashes($row['artist']))."\"></p>";
   $form .= "<p><span class=artist>Song:</span><br><input type='text' name='song' value=\"".htmlentities(stripslashes($row['song']))."\"></p>";
   $form .= "<p><span class=artist>Genre:</span><br><input type='text' name='genre' value=\"".htmlentities(stripslashes($row['genre']))."\"></p>";
   $form .= "<p><span class=artist>MP3:</span><br><input type='hidden' name='submitted' value='TRUE' id='".time()."'><input type='hidden' name='MAX_FILE_SIZE' value='".$max_file_size."'>";
  // Upload files:<br /><input type='hidden' name='submitted' value='TRUE' id='".time()."'><input type='hidden' name='MAX_FILE_SIZE' value='".$max_file_size."'>";
   
   
   for($x=0;$x<$num_of_uploads;$x++){
     $form .= "<input type='file' name='file[]'><br />";
   }
   $form .= "<br />Depending on the size of the MP3, this may take several minutes!<br /><br /><input type='submit' value='Submit Entry'> Valid file type(s): ";
   for($x=0;$x<count($file_types_array);$x++){
     if($x<count($file_types_array)-1){
       $form .= $file_types_array[$x].", ";
     }else{
       $form .= $file_types_array[$x].".";
     }
   }
   $form .= "</form>";
   echo($form);
  }else{
   foreach($_FILES["file"]["error"] as $key => $value){
     if($_FILES["file"]["name"][$key]!=""){
       if($value==UPLOAD_ERR_OK){
       	
       	 $origfilename = $_FILES["file"]["name"][$key];
         $filename = explode(".", $_FILES["file"]["name"][$key]);
         $filenameext = $filename[count($filename)-1];
         unset($filename[count($filename)-1]);
         $filename = implode(".", $filename);
       //  $filename = substr($filename, 0, 15).".".$filenameext;
      $date = date("mdY"); 
  			$time = date("His");
    //  $artist = $_POST['artist'];
    //  $song = $_POST['song'];
      
       $filename = $date.$time.".".$filenameext;
       // $filename = $artist."-".$song.".".$filenameext;
         $file_ext_allow = FALSE;
         for($x=0;$x<count($file_types_array);$x++){
           if($filenameext==$file_types_array[$x]){
             $file_ext_allow = TRUE;
           }
         }
         if($file_ext_allow){
           if($_FILES["file"]["size"][$key]<$max_file_size){
             if(move_uploaded_file($_FILES["file"]["tmp_name"][$key], $upload_dir.$filename)){
             	
             	//	$mp3_upload = $_FILES['mp3_name'];
           	$file_size = $_FILES['file']['size'][$key];
           	
           //	$date = date("mdY"); 
  			//$time = date("His");
  			//$mp3_dir = "mp3";
           	
           $filename = $date.$time.".mp3";
			// Store the orignal file
			//copy($mp3_upload, $mp3_dir."/".$filename);
             	
             	
             	  $query = "INSERT INTO music_archives SET "
  				." artist='".addslashes($_POST['artist'])."'"
				.", song='".addslashes($_POST['song'])."'"
				.", genre='".addslashes($_POST['genre'])."'"
				.", mp3_name='$filename'"
				.", mp3_size='$file_size'"
				.", entry=now()";
  $result = mysql_query($query) or die("Error: ".mysql_error());
         ?>
         
          <script language="JavaScript">

  var count= 0



  function wait() {

    count ++

    if(count == 1 ){

      window.document.location.href='adminadd.php'

    }

    else{

      setTimeout("wait()",1000)

    }

  }



  wait();

  </script>

         
         <?    	
              // echo("File uploaded successfully. - <a href='".$upload_dir.$filename."' target='_blank'>".$filename."</a><br />");
             }else{
               echo($origfilename." was not successfully uploaded<br />");
             }
           }else{
             echo($origfilename." was too big, not uploaded<br />");
           }
         }else{
           echo($origfilename." had an invalid file extension, not uploaded<br />");
         }
       }else{
         echo($origfilename." was not successfully uploaded<br />");
       }
     }
   }
  }
}
?>
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS