i’ve found this code on a website for uploading files using javascript, but it doesn’t seems to work. Could somebody help me with that please?
Index.php :
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <link href="style.css" rel="stylesheet" type="text/css"/> </head> <body> <div class="container"> <div class="row"> <div id="uploads"></div> <div class="dropzone" id="dropzone"> Drop files fere to upload </div> </div> </div> <script src="js_script.js" type="text/javascript"></script> </body> </html>
And js :
(function() { var dropzone = document.getElementById('dropzone'); var displayUploads = function(data) { var uploads = document.getElementById('uploads'), anchor, x; for (x = 0; x < data.length; x = x + 1) { anchor = document.createElement('a'); anchor.href = data[x].file; anchor.innerText = data[x].name; uploads.appendChild(anchor); } }; var upload = function(files) { var formData = new FormData(), xhr = new XMLHttpRequest(), x; for (x = 0; x < files.length; x = x + 1) { formData.append('file[]', files[x]); } xhr.onload = function() { var data = JSON.parse(this.responseText); displayUploads(data); }; xhr.open('post', 'upload.php'); xhr.send(formData); }; dropzone.ondrop = function(e) { e.preventDefault(); this.className = 'dropzone'; upload(e.dataTransfer.files); }; dropzone.ondragover = function() { this.className = 'dropzone dragover'; return false; }; dropzone.ondragleave = function() { this.className = 'dropzone'; return false; }; }());
and upload.php :
<?php header("Content-Type: application/json"); $uploaded = array(); if(!empty($_FILES['file']['name'][0])){ foreach($_FILES['file']['name'] as $position => $name){ if(move_uploaded_file($_FILES['file']['tmp_name'][$position], 'uploads/'.$name)){ $uploaded[] = array( 'name' => $name, 'file' => 'uploads/'.$name ); } } } echo json_encode($uploaded); ?>
And now this issue :
GET …/upload.php 404 (Not Found)
and related code to issue :
xhr.send(formData);
btw what is that “GET” showing in console??
Advertisement
Answer
I just saved the file “Upload.php” with uppercase “U” which should be “upload.php”.