Tenho o seguinte código para upload de imagem porém só funciona se o js estiver na mesma página do formulário e não funciona vindo o js de arquivo externo, gostaria de usar externo por que uso outras funções, alguém poderia me explicar o por que não funciona o js externo ou dar alguma dica? agradecido!
HTML
<head>
<title>Image Upload Form</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/teste.js"></script>
</head>
<body>
<form method="post" id="fileinfo" name="fileinfo" ">
<label>Select a file:</label><br>
<input type="file" name="file" required onchange='return submitForm();'/>
<input type="submit" value="Upload" />
</form>
<div id="output"></div>
js externo
function submitForm() {
console.log("submit event");
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("label", "WEBUPLOAD");
$.ajax({
url: "../teste.php",
type: "POST",
data: fd,
processData: false,
contentType: false
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
Php
if ($_POST["label"]) {
$label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$filename = $label.$_FILES["file"]["name"];
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $filename)) {
echo $filename . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $filename);
echo "Stored in: " . "upload/" . $filename;
}
}
} else {
echo "Invalid file";
}
?>