Skip to content

Instantly share code, notes, and snippets.

@henriqueutsch
Created October 26, 2015 20:54
Show Gist options
  • Save henriqueutsch/7a5dc6af24646550b138 to your computer and use it in GitHub Desktop.
Save henriqueutsch/7a5dc6af24646550b138 to your computer and use it in GitHub Desktop.
UPLOAD FILE AJAX PHP
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery-1.11.0.min.js"></script>
<script>
$( document ).ready(function() {
var form;
$('#fileupload').change(function (event) {
form = new FormData();
form.append('userfile', event.target.files[0]); // para apenas 1
$.ajax({
type: "post", // Defino o método de envio POST / GET
url: 'upload.php', // Informo a URL que será pesquisada.
data: form,
processData: false,
contentType: false,
success: function(html){
// alert(html); // Adiciono o valor dentro do elemento.
$("#filename").val(html);
}
});
});
$( "#formupload" ).submit(function( event ) {
event.preventDefault();
var serializedData = $('#formupload').serialize();
alert(serializedData);
$.ajax({
type: "post", // Defino o método de envio POST / GET
url: 'envia.php', // Informo a URL que será pesquisada.
data: form,
success: function(html){
alert(html); // Adiciono o valor dentro do elemento.
// $("#respostanovidades").html(html);
}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post" id="formupload">
<input type="hidden" name="filename" value="" id="filename"/>
Enviar esse arquivo: <input id="fileupload" name="userfile" type="file" /><br>
nome: <input type="text" name="nome">
<input type="submit" value="Enviar arquivo" />
</form>
</body>
</html>
<?php
// Nas versões do PHP anteriores a 4.1.0, $HTTP_POST_FILES deve ser utilizado ao invés
// de $_FILES.
$uploaddir = '/www/upload/upload/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// echo "Arquivo valido e enviado com sucesso.\n";
echo $_FILES['userfile']['name'];
} else {
echo "Possível ataque de upload de arquivo!\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment