Created
March 6, 2018 21:33
-
-
Save danielbonifacio/7196dcf34a0da7856578caf6906393bd to your computer and use it in GitHub Desktop.
Upload de arquivo com AJAX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if(isset($_FILES['arquivo'])): | |
$allowed_extensions = ['jpg', 'png', 'zip', 'rar']; | |
$nome_arquivo = $_FILES['arquivo']['name']; | |
$explode = explode(".",$nome_arquivo); | |
$extensao = end($explode); | |
//Verifica se a extensão do arquivo é permitida | |
if(!in_array($extensao, $allowed_extensions)): | |
echo "extensão do arquivo não permitida"; | |
exit; | |
else: | |
$novo_nome = $nome_arquivo; | |
$diretorio = "./arquivos/"; | |
$enviado = move_uploaded_file($_FILES['arquivo']['tmp_name'], $diretorio.$novo_nome); | |
if($enviado): | |
echo "enviado"; | |
exit; | |
else: | |
echo "erro"; | |
exit; | |
endif; | |
endif; | |
else: | |
echo "nenhuma imagem foi enviada"; | |
exit; | |
endif; | |
?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Tutorial Ajax Envio de Arquivos</title> | |
</head> | |
<body> | |
<input type="file" id="arquivo"> | |
<button id="enviaArquivo">Enviar Arquivo</button> | |
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> | |
<script> | |
$(document).on('click', '#enviaArquivo', function(e){ | |
e.preventDefault(); | |
let arquivo = new FormData(); | |
arquivo.append('arquivo', $('#arquivo').prop('files')[0]); | |
$.ajax({ | |
url: '/arquivo.php', | |
method: 'POST', | |
data: arquivo, | |
cache: false, | |
processData: false, | |
contentType: false | |
}).done(function(data){ | |
console.log(data); | |
}); | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment