2

I'm working on upload form for mp3 files and I hit a wall :/. Can you help please?

Here is my HTML:

<form id="file-form" method="POST">
<input class="profileMenu" id="mp3file" name="mp3file" type="file" multiple/>    
</form>
<div onclick="test()" class="col-md-1 profileMenu" id="uploadButton">Upload</div> 

Here is my JavaScript:

function test() {
var form = document.getElementById('file-form');
var fileSelect = document.getElementById('mp3file');
var uploadButton = document.getElementById('uploadButton');

uploadButton.innerHTML = 'Uploading...';

var files = fileSelect.files;
var formData = new FormData();

for (var i = 0; i < files.length; i++) {
    var file = files[i];
    formData.append('mp3file', file, file.name);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'php/commercial/upload.php', true);
    xhr.onload = function () {
        if (xhr.status === 200) {
            uploadButton.innerHTML = 'Upload';
        }
        else {
            alert('An error occurred!');
        }
    };
    xhr.send(formData);
}    
}

And lastly my PHP:

<?php
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['filename']['name']); 

if(move_uploaded_file($_FILES['filename']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['filename']['name']). " has been uploaded"; 
} else{
    echo "There was an error uploading the file, please try again!";
}
?>

I'm trying to upload mp3 files to my server and sort them in folders, form validation is going ok, request doesn't return any errors and it seems my php code is not doing what it should be, I know i can do it with submit button without using JavaScript but i need to do it this way. So if any of you have any idea i would be very thankful.

chris85
  • 23,846
  • 7
  • 34
  • 51
Bruno
  • 21
  • 5
  • Here is php error_log: Undefined index: filename in /home/brunodev/public_html/UltraBox/user/php/commercial/upload.php on line 4 Undefined index: filename in home/brunodev/public_html/UltraBox/user/php/commercial/upload.php on line 5 – Bruno Sep 20 '15 at 21:01
  • Try adding `enctype="multipart/form-data"` attribute to the form. – Matt O'Connell Sep 20 '15 at 21:09
  • @Bruno you should add the error message(s) to your question. – chris85 Sep 20 '15 at 21:14

0 Answers0