Hey everyone,

I'm trying to create a form to upload files and create links from the uploaded files to download for whoever visits that particular page. I've gotten the files to upload to the folder and display as a link but whenever I refresh the page, the links go away, yet the files are still in the folder in the same directory as the html/php file to upload the file. How do I go about fixing this?

upload.php

<?php

if(!empty($_FILES["file"])){
    foreach($_FILES["file"]["name"] as $key => $name){
        if($_FILES["file"]["error"][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
            $uploaded[] = $name;
        }
    }

    if(!empty($_POST['ajax'])){
        die(json_encode($uploaded));
    }
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html version="-//W3C//DTD XHTML 1.1//EN"
      xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.w3.org/1999/xhtml
                          http://www.w3.org/MarkUp/SCHEMA/xhtml11.xsd">
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <script type="text/javascript" src="upload.js"></script>
        <style type="text/css">
            #upload_progress{
                display: none;
            }
        </style>
        <title>File Upload</title>
    </head>
    <body>
        <div id="uploaded">
            <?php

                if(!empty($uploaded)){
                    foreach($uploaded as $name){
                        echo '<div><a href="files/', $name, '">', $name, '</a></div>';
                    }
                }

            ?>
        </div>
        <div id="upload_progress"></div>
        <div>
            <form action="" method="post" enctype="multipart/form-data">
                <div>
                    <input type="file" id="file" name="file[]" multiple="multiple" />
                    <input type="submit" id="submit" value="Upload" />
                </div>
            </form>
        </div>
    </body>
</html>

upload.js

var handleUpload = function(event){
    event.preventDefault();
    event.stopPropagation();

    var fileInput = document.getElementById('file');

    var data = new FormData();

    data.append('ajax', true);

    for (var i = 0; i < fileInput.files.length; ++i){
        data.append('file[]', fileInput.files[i]);
    }
    var request = new XMLHttpRequest();

    request.upload.addEventListener('progress', function(event){
        if (event.lengthComputable){
            var percent = event.loaded / event.total;
            var progress = document.getElementById('upload_progress');

            while(progress.hasChildNodes()){
                progress.removeChild(progress.firstChild);
            }

            progress.appendChild(document.createTextNode(Math.round(percent * 100) + ' %'));
        }
    });

    request.upload.addEventListener('load', function(event){
        document.getElementById('upload_progress').style.display = 'none';
    });

    request.upload.addEventListener('error', function(event){
        alert("Upload Failed");
    });

    request.addEventListener('readystatechange', function(event){
        if(this.readyState == 4){
            if(this.status == 200){
               var links = document.getElementById('uploaded');

               console.log(this.response);
               var uploaded = eval(this.response);
               var div, a;

               for(var i = 0; i < uploaded.length; ++i){
                div = document.createElement('div');
                a = document.createElement('a');

                a.setAttribute('href', 'files/' + uploaded[i]);
                a.appendChild(document.createTextNode(uploaded[i]));

                div.appendChild(a);
                links.appendChild(div);
               }
            }else{
                console.log('Server replied with HTTP status ' + this.status);
            }
        }
    });

    request.open('POST', 'upload.php');
    request.setRequestHeader('Cache-Control', 'no-cache');

    document.getElementById('upload_progress').style.display = 'block';

    request.send(data);
}

window.addEventListener('load', function(event){
    var submit = ducument.getElementById('submit');
    submit.addEventListener('click', handleUpload)
});

Thanks in advance!

Re: keeping links displayed from files uploaded through ajax, php 80 80

How do I go about fixing this?

You can store the file paths in the database, or use glob to get the files in the folder, and display them as links.

Re: keeping links displayed from files uploaded through ajax, php 80 80

Is there a way where I don't have to you a database and just store them in a folder to display?

Re: keeping links displayed from files uploaded through ajax, php 80 80

use glob to get the files in the folder

Re: keeping links displayed from files uploaded through ajax, php 80 80

dumb question but how do I do that? I tried inserting the glob() in the while loop but it showed an error..

Re: keeping links displayed from files uploaded through ajax, php 80 80

Example in the manual. Should be something like glob('files/*') which returns an array.

Re: keeping links displayed from files uploaded through ajax, php 80 80

Okay, this is getting way too complicated.. The upload form works as far as uploading the document but I just want the folder to display the the contents of a folder and make a link out of it that stays on the page after a refresh.

Once I submit a file to the form, it does show a link to the file but it disapears after I refresh the page. What can I do with the code that I have displayed to fix this issue? If the glob function is what I need to use, I'm apparently not using it right. Any ideas?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.