PHP Script Forums » PHP Classes Support Forum

[sticky] [closed]

PHP / Ajax upload example

(62 posts)
Please support us by buying these products:

  1. Olaf

    Olaf
    PHP Coder

    While the upload via XMLHttpRequest is not possible are there many examples and tutorials to upload file via some "virtual IFRAME".

    In this quick tutorial we will show how-to create such an Ajax upload form using the jQuery Form plug-in and our easy upload class. There is also a upload demo page available if you like to have a quick view on how it works. Okay let's start...

    The system is very simple, build your upload form just like normal. In place of posting the form to the script you use some JavaScript code to post the data to some PHP script in the background.

    Requirements

    Download the required files and place the JavaScript files into the same directory as your HTML document and place the following JavaScript code into the HTML header:

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="jquery.form.js"></script>
    <script type="text/javascript">
    
    $(document).ready(function() {
    	$("#loading")
    	.ajaxStart(function(){
    		$(this).show();
    	})
    	.ajaxComplete(function(){
    		$(this).hide();
    	});
    	var options = {
    		beforeSubmit:  showRequest,
    		success:       showResponse,
    		url:       'upload4jquery.php',  // your upload script
    		dataType:  'json'
    	};
    	$('#Form1').submit(function() {
    		document.getElementById('message').innerHTML = '';
    		$(this).ajaxSubmit(options);
    		return false;
    	});
    }); 
    
    function showRequest(formData, jqForm, options) {
    	var fileToUploadValue = $('input[@name=fileToUpload]').fieldValue();
    	if (!fileToUploadValue[0]) {
    		document.getElementById('message').innerHTML = 'Please select a file.';
    		return false;
    	} 
    
    	return true;
    } 
    
    function showResponse(data, statusText)  {
    	if (statusText == 'success') {
    		if (data.img != '') {
    			document.getElementById('result').innerHTML = '<img src="/upload/thumb/'+data.img+'" />';
    			document.getElementById('message').innerHTML = data.error;
    		} else {
    			document.getElementById('message').innerHTML = data.error;
    		}
    	} else {
    		document.getElementById('message').innerHTML = 'Unknown error!';
    	}
    } 
    
    </script>

    Next create a PHP script named "upload4jquery.php" and place it in the same directory where other files are located. Place this code into that new file:

    <?php
    include($_SERVER['DOCUMENT_ROOT'].'/classes/upload/foto_upload_script.php');
    
    $foto_upload = new Foto_upload;	
    
    $json['size'] = $_POST['MAX_FILE_SIZE'];
    $json['img'] = '';
    
    $foto_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/upload/";
    $foto_upload->foto_folder = $_SERVER['DOCUMENT_ROOT']."/upload/";
    $foto_upload->thumb_folder = $_SERVER['DOCUMENT_ROOT']."/upload/thumb/";
    $foto_upload->extensions = array(".jpg", ".gif", ".png");
    $foto_upload->language = "en";
    $foto_upload->x_max_size = 480;
    $foto_upload->y_max_size = 360;
    $foto_upload->x_max_thumb_size = 120;
    $foto_upload->y_max_thumb_size = 120;
    
    $foto_upload->the_temp_file = $_FILES['fileToUpload']['tmp_name'];
    $foto_upload->the_file = $_FILES['fileToUpload']['name'];
    $foto_upload->http_error = $_FILES['fileToUpload']['error'];
    $foto_upload->rename_file = true; 
    
    if ($foto_upload->upload()) {
    	$foto_upload->process_image(false, true, true, 80);
    	$json['img'] = $foto_upload->file_copy;
    } 
    
    $json['error'] = strip_tags($foto_upload->show_error_string());
    echo json_encode($json);
    ?>

    This tutorial or guide is not about how to use the easy upload class. If you never used the class before try the example files first and than start with this Ajax upload form.

    Paths and upload directories

    You need to create some upload directories (2 one for the upload and one for the thumbs) and check the permission (chmod the upload directory with 777). If you use the same structure as suggested in the class file you don't need to change the include at the top from the PHP script.

    Now we need the form HTML and some other containers where the response data is placed.

    <form id="Form1" name="Form1" method="post" action="">
        <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>" />
        Select an image from your hard disk:
    
        <div>
            <input type="file" name="fileToUpload" id="fileToUpload" size="18" />
            <input type="Submit" value="Submit" id="buttonForm" />
        </div>
    </form>
    <img id="loading" src="loading.gif" style="display:none;" />
    
    <p id="message">
    
    <p id="result">

    The file loading.gif is the upload indicator image, pick the I used on the demo page or check Google for more stylish images or image generators.

    Some final note, the code works as it is. Don't change name or if attributes if you not sure if you use them inside the JavaScript code.

    Posted 10 months ago #
  2. User has not uploaded an avatar

    Jet
    Member

    Hi Olaf,

    As usual, everything works out of the box. The only minor exception being, it seems, that the latest classes zip file now contains an extra file - foto_upload_script.php

    The Easy Upload Class plus your instructions above form a very good and complete set of PHP, Mysql Ajax upload scripts.

    Thank you Olaf.

    Posted 9 months ago #
  3. Olaf

    Olaf
    PHP Coder

    Yes right this file is without the example code, I will split them for good and post an update. Thanks for mentioning.

    Posted 9 months ago #
  4. User has not uploaded an avatar

    90210
    Member

    include($_SERVER['DOCUMENT_ROOT'].'/classes/upload/foto_upload_script.php');
    where can I download this file?

    Posted 9 months ago #
  5. User has not uploaded an avatar

    rizmedh
    Member

    @90210
    you can download in Easy Upload PHP class..
    but the problem, why my image when i upload not showing??
    because there are no thumbs that created in my files.
    help me.

    Posted 9 months ago #
  6. User has not uploaded an avatar

    rizmedh
    Member

    thanks, now its work, i was setting image_magick = false .. =)

    Posted 9 months ago #
  7. User has not uploaded an avatar

    90210
    Member

    how can I upload media files like .avi and .mpeg instead of picture files?

    Posted 9 months ago #
  8. Olaf

    Olaf
    PHP Coder

    Hi,

    just add the extension to the code:
    $foto_upload->extensions = array(".jpg", ".gif", ".png");

    not if you like to show the content after upload you need to change the html too (don't use the image tag for videos)

    Posted 9 months ago #
  9. bicho44

    bicho44
    Member

    Hi:
    Maybe it to much, but can i upload a .zip file, then unzip it and then move to another directory watermarking the image in the way?

    I know, i know im a little bit...(you know) but was a question i was having and maybe someone can point me some directions.

    TIA

    Fede

    Posted 9 months ago #
  10. Olaf

    Olaf
    PHP Coder

    Hi,

    why do you need to zip that file? is the file so big?

    Posted 9 months ago #

RSS feed for this topic

Topic Closed

This topic has been closed to new replies.