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 :
JavaScript
x
21
21
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<meta charset="UTF-8">
5
<title></title>
6
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
7
<link href="style.css" rel="stylesheet" type="text/css"/>
8
</head>
9
<body>
10
<div class="container">
11
<div class="row">
12
<div id="uploads"></div>
13
<div class="dropzone" id="dropzone">
14
Drop files fere to upload
15
</div>
16
</div>
17
</div>
18
<script src="js_script.js" type="text/javascript"></script>
19
</body>
20
</html>
21
And js :
JavaScript
1
52
52
1
(function() {
2
var dropzone = document.getElementById('dropzone');
3
4
var displayUploads = function(data) {
5
var uploads = document.getElementById('uploads'),
6
anchor,
7
x;
8
for (x = 0; x < data.length; x = x + 1) {
9
anchor = document.createElement('a');
10
anchor.href = data[x].file;
11
anchor.innerText = data[x].name;
12
13
uploads.appendChild(anchor);
14
}
15
};
16
17
var upload = function(files) {
18
19
var formData = new FormData(),
20
xhr = new XMLHttpRequest(),
21
x;
22
for (x = 0; x < files.length; x = x + 1) {
23
formData.append('file[]', files[x]);
24
}
25
26
xhr.onload = function() {
27
var data = JSON.parse(this.responseText);
28
displayUploads(data);
29
};
30
31
xhr.open('post', 'upload.php');
32
xhr.send(formData);
33
34
};
35
36
dropzone.ondrop = function(e) {
37
e.preventDefault();
38
this.className = 'dropzone';
39
upload(e.dataTransfer.files);
40
};
41
42
dropzone.ondragover = function() {
43
this.className = 'dropzone dragover';
44
return false;
45
};
46
47
dropzone.ondragleave = function() {
48
this.className = 'dropzone';
49
return false;
50
};
51
}());
52
and upload.php :
JavaScript
1
20
20
1
<?php
2
3
header("Content-Type: application/json");
4
$uploaded = array();
5
if(!empty($_FILES['file']['name'][0])){
6
7
foreach($_FILES['file']['name'] as $position => $name){
8
9
if(move_uploaded_file($_FILES['file']['tmp_name'][$position], 'uploads/'.$name)){
10
$uploaded[] = array(
11
'name' => $name,
12
'file' => 'uploads/'.$name
13
);
14
}
15
}
16
}
17
echo json_encode($uploaded);
18
19
?>
20
And now this issue :
GET …/upload.php 404 (Not Found)
and related code to issue :
JavaScript
1
2
1
xhr.send(formData);
2
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”.