简体   繁体   中英

PHP AJAX Image Upload Example Not Uploading

My code produces no errors on the console. When I click the upload button, nothing happens. There is a post sent to itself, as instructed in the tutorial I used but the image is not uploaded to my folder and it is not displayed on my page. Barring the fact I know I should use jquery (I will make the transition once I get it to upload to the folder) what is wrong with my code?

<?php

if (!empty($_FILES)) {
    $name = $_FILES['file']['name'];

    if ($_FILES['file']['error'] == 0) {move_uploaded_file($_FILES['file']
            ['tmp_name'], "post_images/" . $name))} 
}

?>



<script type="text/javascript">

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

var fileInput = document.getElementById('file');
var data = new FormData();  
data.append('file', fileInput.files[1]);    
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.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 = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});

</script>


<div id="uploaded">

<?php

if (!empty($name)) {

echo '<img src="post_images/' . $name . '" width="100" height="100" />';    

}

?>

</div>

<div id="upload_progress"></div>

<div>

<form action="" method="post" enctype="multipart/form-data">

<div>

    <input type="file" id="file" name="file" />
    <input type="submit" id="submit" value="upload" />

</div>

</form>

</div>

非多个文件输入元素中只有一个文件, fileInput.files[1]尝试使用第二个文件。

data.append('file', fileInput.files[0]);    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM