0

I am creating a file upload script.

What I wanted to do is to upload the file without refreshing the page

Here's my code:

upload.php

<?php
function upload(){
if(!empty($_FILES['file1']['name'][0])){

$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');

foreach ($files ['name'] as $position => $file_name) {

    $file_tmp = $files['tmp_name'][$position];
    $file_size = $files['size'][$position];
    $file_error = $files['error'][$position];

    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));

    if (in_array($file_ext,$allowed)) {
        if ($file_error === 0) {
            if($file_size<=20971520){
                $file_name_new = uniqid('',true).'.'.$file_ext;
                $file_destination = 'test_uploads/'.$file_name_new;

                if (move_uploaded_file($file_tmp, $file_destination)) {
                    $uploaded[$position] = $file_destination;
                }else{
                    $failed[$position] = '[{$file_name}] failed to upload!';
                }
            }else{
                $failed[$position] = '[{$file_name}] file is too large!';
            }
        }else {
        $failed[$position] = '[{$file_name}] file extension is not allowed!';
        }
    }else{
        $failed[$position] = '[{$file_name}] file extension not allowed!';
    }
}

if (!empty($uploaded)) {
    print_r($uploaded);
}

if (!empty($failed)) {
    print_r($failed);
}
}
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
<input type="file" name="file1[]" id="file1" multiple>
<input type="button" value="Upload File" onclick ="document.write('<?php upload(); ?>'')">
</form>

</body>
</html>

I wanted to do this on AJAX, I already searched for some examples but I want this to be simpler as possible.

By the way, is it possible for this to run without using any plugins or libraries?

2
  • There are to many ways to fix this... What is your definition of simple? What have you tried already? And yes... it is possible to do this without plugins and libraries... tl;dr your question is too broad Commented Nov 27, 2014 at 10:38
  • You cant call a PHP function with document.write. Commented Nov 27, 2014 at 10:54

3 Answers 3

1

I managed to find a solution for this. I separated the php script from the html and add a javascript file. I used ajax to call the PHP file to upload the files.

Here's my code;

index.php

<html>
<head>
<style type="text/css">

.upload{
width:500px;
background:#f0f0f0;
border: 1px solid #ddd;
padding: 20px;
}
.upload fieldset{
border: 0;
padding: 0;
margin-bottom:10px; 
}

.uploads a, .uploads span{
display: block;
}

.bar{
width: 100%;
background: #eee;
padding: 3px;
margin-bottom:10px; 
box-shadow: inset 0 1px 3px rgba(0,0,0,2);
border-radius: 3px;
box-sizing:border-box;
}
.barfill{
height: 20px;
display: block;
background: #ff6f01;
width:0px;
border-radius: 3px;
transition:width 0.8s ease;
}

.barfilltext{
color:#fff;
padding: 3px;
}
</style>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
    <fieldset>
        <legend>Upload Files</legend>
        <input type="file" id="file" name="file[]" required multiple>
        <input type="button" id="submit" value="Upload">
    </fieldset>
    <div class="bar">
        <span class="barfill" id="pb"><span class="barfilltext" id="pt">40%</span></span>
    </div>
    <div id="uploads" class="uploads">

    </div>
    <script type="text/javascript" src="upload.js"></script>

    <script type="text/javascript">
        document.getElementById('submit').addEventListener('click', function(e){
                e.preventDefault();
            var f = document.getElementById('file'),
                pb = document.getElementById('pb'),
                pt = document.getElementById('pt');

                    app.uploader({
                    files:f,
                    progressBar:pb,
                    progressText:pt,
                    processor: 'upload.php',

                    finished: function(data){
                        var uploads = document.getElementById('uploads'),
                            succeeded = document.createElement('div'),
                            failed = document.createElement('div'), anchor, span, x;

                            if (data.failed.length) {
                                failed.innerHTML = '<p>The following files failed to upload</p>'

                            }
                            uploads.innerText = '' ;
                            for(x=0; x<data.succeeded.length; x = x+1){
                                anchor = document.createElement('a');
                                anchor.href = 'uploads/' + data.succeeded[x].file;
                                anchor.innerText = data.succeeded[x].name;
                                anchor.target = '_blank';
                                succeeded.appendChild(anchor);
                            }
                            for(x=0;x<data.failed.length; x=x+1){
                                span = document.createElement('span');
                                span.innerText = data.failed[x].name;

                                failed.appendChild(span);   
                            }
                            uploads.appendChild(succeeded);
                            uploads.appendChild(failed);
                    },


                    error: function (){
                        console.log("Error");
                    }
                });
            });
    </script>
</form>
</body>
</html>

upload.php

<?php
header('Content-Type: application/json');
$uploaded = [];
$allowed = ['jpg'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file'])) {

foreach ($_FILES['file']['name'] as $key => $name) {

    if($_FILES['file']['error'][$key] === 0){
        $temp = $_FILES['file']['tmp_name'][$key];
        $ext = explode('.', $name);
        $ext = strtolower(end($ext));

        $file = md5_file($temp) . time() .'.'.$ext;

        if (in_array($ext,$allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
                $succeeded [] = array('name' => $name, 'file' => $file);

            # code...
        }else{
            $failed[] = array('name' => $name );
        }

    }else{

        echo "Error";
    }
  }
}

if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded, 
'failed' =>$failed
));
}
?>

upload.js

var app = app || {};
(function (obj) {
"use stricts;"
//Private Methods
var ajax, getFormData, setProgress;

ajax = function(data){
    var xmlhttp = new XMLHttpRequest(), uploaded;
    xmlhttp.addEventListener('readystatechange', function(){
        if (this.readyState === 4) {
            if (this.status === 200) {
                uploaded = JSON.parse(this.response);
                if (typeof obj.options.finished === 'function') {
                    obj.options.finished(uploaded);
                }
            }else{
                if (typeof obj.options.error === 'function') {
                    obj.options.error();
                }
            }
        }
    });
    xmlhttp.upload.addEventListener('progress',function(){
        var percent;

        if (event.lengthComputable === true) {
            percent = Math.round((event.loaded / event.total) * 100);
            setProgress(percent);
        }
    });

    xmlhttp.open('post', obj.options.processor);
    xmlhttp.send(data);

};

getFormData = function(source){
    var data = new FormData(), i;

    for(i=0; i<source.length; i = i+1){
        data.append('file[]',source[i]);
    }
    data.append('ajax', true);
    return data;
};

setProgress = function (value){
    if (obj.options.progressBar !== undefined) {
        obj.options.progressBar.style.width = value ? value + '%': 0;
    }

    if (obj.options.progressText !== undefined) {
        obj.options.progressText.innerText = value ? value + '%' : 0; 
    }
};

obj.uploader = function(options){
    obj.options = options;

    if (obj.options.files !== undefined) {
        ajax(getFormData(obj.options.files.files));
    }
}
}(app));

anyways, thanks for the help guys. those were gladly appreciated. Thanks!

Sign up to request clarification or add additional context in comments.

Comments

0

I think in your case the simplest way is to put it into an iframe. I assume you have all code in one PHP file which is called upload.php. You would get something like this:

<?php

//Check if the action is upload file. If it is start upload
if(isset($_GET['action']) && $_GET['action'] == 'uploadFile')
{
    if(!empty($_FILES['file1']['name'][0])){

        $files = $_FILES['file1'];
        $uploaded = array();
        $failed = array();
        $allowed = array('jpg','txt','png');

        foreach ($files ['name'] as $position => $file_name) {
            $file_tmp = $files['tmp_name'][$position];
            $file_size = $files['size'][$position];
            $file_error = $files['error'][$position];

            $file_ext = explode('.', $file_name);
            $file_ext = strtolower(end($file_ext));

            if (in_array($file_ext,$allowed)) {
                if ($file_error === 0) {
                    if($file_size<=20971520){
                        $file_name_new = uniqid('',true).'.'.$file_ext;
                        $file_destination = 'test_uploads/'.$file_name_new;

                        if (move_uploaded_file($file_tmp, $file_destination)) {
                            $uploaded[$position] = $file_destination;
                        }else{
                            $failed[$position] = '[{$file_name}] failed to upload!';
                        }
                    }else{
                        $failed[$position] = '[{$file_name}] file is too large!';
                    }
                }else {
                $failed[$position] = '[{$file_name}] file extension is not allowed!';
                }
            }else{
                $failed[$position] = '[{$file_name}] file extension not allowed!';
            }
        }

        if (!empty($uploaded)) {
            print_r($uploaded);
        }

        if (!empty($failed)) {
            print_r($failed);
        }
    }
    exit;
}
//Check if the action is getForm. If it is then display the form. This is to display the form in the iframe
elseif(isset($_GET['action']) && $_GET['action'] == 'getForm')
{
    echo '
    <form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php?action=uploadFile">
    <input type="file" name="file1[]" id="file1" multiple>
    <input type="submit" value="Upload File">
    </form>';   
    exit;
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
    <!-- IFrame which loads the form !-->
    <iframe id="uploadFileFrame" style="width:100%; height:auto; border:0px;" src="upload.php?action=getForm"></frame>
</body>
</html>

Comments

0

Showing uploaded image after successful upload

you just go through with this code I have already given the answer of this type of question

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.