Created
September 11, 2018 20:23
-
-
Save fabiobusnello/2259bc6b2ef9c670b9c8a284dfc3539e to your computer and use it in GitHub Desktop.
Send Files and Fields, php and jquery single-file
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 | |
@$files = $_FILES['files']; // aqui eu pego todos os arquivos que estiverem no campo files | |
@$name = $_POST['name']; // aqui eu pego o campo com o name="name" do formulário | |
$returnJson = array(); | |
if($files){ | |
array_push($returnJson, $files); | |
//var_dump($files); | |
} | |
if($name){ | |
array_push($returnJson, $name); | |
//var_dump($name); | |
} | |
if($files || $name){ | |
echo json_encode($returnJson); | |
return true; | |
} | |
?> | |
<!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>Document</title> | |
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> | |
</head> | |
<body> | |
<div> | |
<input type="file" multiple accept="image/png,image/jpg" id="files"> | |
<input type="text" id="name"> | |
<input type="button" value="Enviar" onclick="send()"> | |
</div> | |
<script> | |
const send = () => { | |
//cria um formulário para enviar via ajax | |
const form = new FormData() | |
const files = document.getElementById('files').files | |
//como o campo files é do tipo multiple, ou seja, recebe uma matriz de arquivos então precisamos percorrer esses arquivos e setar dentro do nosso formulário | |
if(files.length){ | |
for(i=0; i < files.length; i++){ | |
form.append('files', files[i], files[i].name) | |
} | |
} | |
// seta o campo name para o formulário | |
form.append('name', document.getElementById('name').value) | |
$.ajax({ | |
url: 'sendFilesAndFields.php', | |
type: 'POST', | |
data: form, | |
dataType: 'json', | |
processData: false, | |
contentType: false, | |
success: (data)=>{console.log(data)}, | |
error: (err, textStatus, errorThrown)=>{console.log(errorThrown)} | |
}) | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment