Good evening, I'm trying to make an image prewier in a file field with multiple uploads.
html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Upload Ajax</title>
<script type="text/javascript" src="../../_global/_funcoes/_js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="_js/upload.js"></script>
</head>
<body>
<div id="principal">
<h1>Envie suas Fotos</h1>
<form action="upload.php" enctype="multipart/form-data" method="post">
<input type="file" name="fotos" id="fotos" multiple>
<button type="submit" id="botao">Enviar Fotos</button>
</form>
<div id="resposta"></div>
<ul id="listaFotos"></ul>
</div>
</body>
</html>
js
// JavaScript Document
(function () {
var input = document.getElementById("fotos"),
formdata = false;
function exibeItem (fonte) {
var lista = document.getElementById("listaFotos"),
li = document.createElement("li"),
img = document.createElement("img");
img.src = fonte;
li.appendChild(img);
lista.appendChild(li);
}
if(window.FormData) {
formdata = new FormData ();
document.getElementById("botao").style.display = "none";
}
input.addEventListener("change", function (evt) {
document.getElementById("resposta").innerHTML = "Enviando Fotos..."
var i = 0, len = this.files.length, img, reader, file;
for (; i < len; i++) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if (window.FileReader) {
reader = new FileReader ();
reader.onloadend = function (e) {
exibeItem (e.target.result, file.fileName);
};
reader.readAsDataUrl(file);
}
if(formdata) {
formdata.append("fotos[]", file);
}
}
}
if(formdata) {
$.ajax ({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res) {
document.getElementById("resposta").innerHTML = res;
}
});
}
}, false)
}());
php
<?php
foreach ($_FILES["fotos"]["error"] as $key => $error) {
if ( $error == UPLOAD_ERR_OK) {
$name = $_FILES["fotos"]["name"][$key];
move_uploaded_file($_FILES["fotos"]["tmp_name"][$key], "upload".$name);
}
}
echo "<h1>Fotos enviadas com sucesso</h1>";
?>
It happens that the code is stopping at line 2 of the js saying that the element of id "button" does not exist and exists.
What can it be?