How to Make A PHP-POWERED Drag & Drop Upload Page

in #utopian-io7 years ago (edited)

This tutorial is to help you create a drag and drop page using php.

You will also need bootstrap and jquery for this to make things really easy.

All the Codes needed in this tutorial are placed in the ending part of this tutorial for formatting reasons.

STEP 1: Create An Upload Folder

I will assume you already have a project you are working on . So create a new folder and name
it whatever it is you like, In my own case, I'll name it "UPLOAD".

STEP 2: Create your Dependency Files

There are certain files you will need for your project to work and you will need to create them

1: Bootstrap.css (You can simply download this from the internet)

2: mystyle.css (COpy the codes tagged "MYSTYLE.CSS" at the end of this tutorial and copy into a file and name it "mystyle.css")

3: jquery.js ( you can simply download this online)

4: ajax.js (This is a custom script I created to control the whole rag and drop, Just copy the codes tagged AJAX.JS in the codes at the end of this tutorial and name it 'ajax.js' )

Step 3: Create your Index Page

I am going to assume you know how to create an index page with html.

Include all the CSS dependency files in the head

Include all the JS dependency files in the footer ( jquery)

Put the codes tagged "BODY" in the last page of this tutorial in the body section

Now that you have done all of this, go to the next step.

STEP 4: Create a file and name it "UPLOAD.PHP"

You could have named it anything you want but let's name it that, to make things understandable.
After naming it, copy the codes tagged "UPLOAD.PHP" in the last page of this tutorial in it

Now that this is done, the whole thing will work but its time I explain the codes and how you can tinker with them to your taste.

Upload.PHP

This is a very important file and here, i explain some of the codes in it.

$dir = 'uploads';

This represents the name of folder to store the uploaded files

Ajax.JS

This is a very important file too and here, I explain some of the codes in it.

acceptedTypes = {
'image/png': true,
'image/jpeg': true,
'image/jpg': true,
'image/gif': true
};

This represents the meme types of the kind of uploads allowed. There are different description words for each file type these are for images, you can search on the internet and check the mime type for your files and add them. As you see , this stated meme types are for images only. IF other files types are uploaded , it will allow it.

There are other parts of code that are good to tinker with and know but then , these are most important. Jquery makes it easy to understand and code java script , so you should find it quite understandable.

Also, bootstrap simply makes everything beautiful.

Body Codes

<div class="container-fluid">
        <div class="row">
            <div class="col-sm-8 col-sm-offset-2">
                <div class="img-zone text-center" id="img-zone">
                    <div class="img-drop">
                        <h2><small>Drag &amp; Drop Photos Here</small></h2>
                        <p><em>- or -</em></p>
                        <h2><i class="glyphicon glyphicon-camera"></i></h2>
                        <span class="btn btn-success btn-file">
                        Click to Open File Browser<input type="file" multiple="" accept="image/*">
                    </span>
                    </div>
                </div>
                <div class="progress hidden">
                    <div style="width: 0%" aria-valuemax="100" aria-valuemin="0" aria-valuenow="0" role="progressbar" class="progress-bar progress-bar-success progress-bar-striped active">
                        <span class="sr-only">0% Complete</span>
                    </div>
                </div>
            </div>
        </div>
        <div id="img-preview" class="row">

        </div>
    </div>

Mystyle.css

body {
            padding-top: 70px;
        }
        .btn-file {
            position: relative;
            overflow: hidden;
        }
        
        .btn-file input[type=file] {
            position: absolute;
            top: 0;
            right: 0;
            min-width: 100%;
            min-height: 100%;
            font-size: 100px;
            text-align: right;
            filter: alpha(opacity=0);
            opacity: 0;
            outline: none;
            background: white;
            cursor: inherit;
            display: block;
        }
        
        .img-zone {
            background-color: #F2FFF9;
            border: 5px dashed #4cae4c;
            border-radius: 5px;
            padding: 20px;
        }
        
        .img-zone h2 {
            margin-top: 0;
        }
        
        .progress,
        #img-preview {
            margin-top: 15px;
        }

AJAX.JS

jQuery(document).ready(function () {
                var img_zone = document.getElementById('img-zone'),     
                collect = {
                    filereader: typeof FileReader != 'undefined',
                    zone: 'draggable' in document.createElement('span'),
                    formdata: !!window.FormData
                }, 
                acceptedTypes = {
                    'image/png': true,
                    'image/jpeg': true,
                    'image/jpg': true,
                    'image/gif': true
                };
                
                // Function to show messages
                function ajax_msg(status, msg) {
                    var the_msg = '<div class="alert alert-'+ (status ? 'success' : 'danger') +'">';
                    the_msg += '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
                    the_msg += msg;
                    the_msg += '</div>';
                    $(the_msg).insertBefore(img_zone);
                }
                
                // Function to upload image through AJAX
                function ajax_upload(files) {                   
                    $('.progress').removeClass('hidden');
                    $('.progress-bar').css({ "width": "0%" });
                    $('.progress-bar span').html('0% complete');    
                                        
                    var formData = new FormData();                  
                    //formData.append('any_var', 'any value');
                    for (var i = 0; i < files.length; i++) {
                        //formData.append('img_file_' + i, files[i]); 
                        formData.append('img_file[]', files[i]);
                    }                       
            
                    $.ajax({
                        url : "upload.php", // Change name according to your php script to handle uploading on server
                        type : 'post',
                        data : formData,
                        dataType : 'json',                      
                        processData: false,
                        contentType: false,
                        error : function(request){
                            ajax_msg(false, 'An error has occured while uploading photo.');                                 
                        },
                        success : function(json){
                            var img_preview = $('#img-preview');
                            var col = '.col-sm-2';
                            $('.progress').addClass('hidden');  
                            var photos = $('<div class="photos"></div>');
                            $(photos).html(json.img);                               
                            var lt = $(col, photos).length;
                            $('col', photos).hide();
                            $(img_preview).prepend(photos.html());
                            $(col + ':lt('+lt+')', img_preview).fadeIn(2000);                                                               
                            if(json.error != '') 
                                ajax_msg(false, json.error);
                        },
                        progress: function(e) {
                            if(e.lengthComputable) {
                                var pct = (e.loaded / e.total) * 100;
                                $('.progress-bar').css({ "width": pct + "%" }); 
                                $('.progress-bar span').html(pct + '% complete');                           
                            }
                            else {
                                console.warn('Content Length not reported!');
                            }
                        }
                    });                 
                }
                
                // Call AJAX upload function on drag and drop event
                function dragHandle(element) {
                    element.ondragover = function () { return false; };
                    element.ondragend = function () { return false; };
                    element.ondrop = function (e) { 
                        e.preventDefault();
                        ajax_upload(e.dataTransfer.files);
                    }       
                }
                
                if (collect.zone) {         
                    dragHandle(img_zone);
                } 
                else {
                    alert("Drag & Drop isn't supported, use Open File Browser to upload photos.");          
                }
            
                // Call AJAX upload function on image selection using file browser button
                $(document).on('change', '.btn-file :file', function() {
                    ajax_upload(this.files);            
                });
                
                // File upload progress event listener
                (function($, window, undefined) {
                    var hasOnProgress = ("onprogress" in $.ajaxSettings.xhr());
                
                    if (!hasOnProgress) {
                        return;
                    }
                    
                    var oldXHR = $.ajaxSettings.xhr;
                    $.ajaxSettings.xhr = function() {
                        var xhr = oldXHR();
                        if(xhr instanceof window.XMLHttpRequest) {
                            xhr.addEventListener('progress', this.progress, false);
                        }
                        
                        if(xhr.upload) {
                            xhr.upload.addEventListener('progress', this.progress, false);
                        }
                        
                        return xhr;
                    };
                })(jQuery, window); 
            });

UPLOAD.PHP

if($_SERVER['REQUEST_METHOD'] == "POST")
{
    $error = '';
    $img = '';
    $dir = 'uploads/';
    $extensions = array("jpeg","jpg","png");
    foreach($_FILES['img_file']['tmp_name'] as $key => $tmp_name )
    {
        $file_name = $_FILES['img_file']['name'][$key];
        $file_size =$_FILES['img_file']['size'][$key];
        $file_tmp =$_FILES['img_file']['tmp_name'][$key];
        $file_type=$_FILES['img_file']['type'][$key];
        $file_ext = strtolower(end(explode('.',$file_name)));  
        if(in_array($file_ext,$extensions ) === true)
        {
            if(move_uploaded_file($file_tmp, $dir.$file_name))
            {
                $img .= '<div class="col-sm-2"><div class="thumbnail">';
                $img .= '<img src="'.$dir.$file_name.'" />';
                $img .= '</div></div>';     
            }
            else
                $error = 'Error in uploading few files. Some files couldn\'t be uploaded.';             
        }   
        else
        {
            $error = 'Error in uploading few files. File type is not allowed.';
        }       
    }
    echo (json_encode(array('error' => $error, 'img' => $img)));    
}
die();



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @akintunde I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.20
TRX 0.13
JST 0.030
BTC 64623.67
ETH 3421.73
USDT 1.00
SBD 2.51